10225501448 李度 10225101546 陈胤遒 10215501422 高宇菲
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1098 lines
33 KiB

Add Env::Remove{File,Dir} which obsolete Env::Delete{File,Dir}. The "DeleteFile" method name causes pain for Windows developers, because <windows.h> #defines a DeleteFile macro to DeleteFileW or DeleteFileA. Current code uses workarounds, like #undefining DeleteFile everywhere an Env is declared, implemented, or used. This CL removes the need for workarounds by renaming Env::DeleteFile to Env::RemoveFile. For consistency, Env::DeleteDir is also renamed to Env::RemoveDir. A few internal methods are also renamed for consistency. Software that supports Windows is expected to migrate any Env implementations and usage to Remove{File,Dir}, and never use the name Env::Delete{File,Dir} in its code. The renaming is done in a backwards-compatible way, at the risk of making it slightly more difficult to build a new correct Env implementation. The backwards compatibility is achieved using the following hacks: 1) Env::Remove{File,Dir} methods are added, with a default implementation that calls into Env::Delete{File,Dir}. This makes old Env implementations compatible with code that calls into the updated API. 2) The Env::Delete{File,Dir} methods are no longer pure virtuals. Instead, they gain a default implementation that calls into Env::Remove{File,Dir}. This makes updated Env implementations compatible with code that calls into the old API. The cost of this approach is that it's possible to write an Env without overriding either Rename{File,Dir} or Delete{File,Dir}, without getting a compiler warning. However, attempting to run the test suite will immediately fail with an infinite call stack ending in {Remove,Delete}{File,Dir}, making developers aware of the problem. PiperOrigin-RevId: 288710907
5 years ago
Release 1.18 Changes are: * Update version number to 1.18 * Replace the basic fprintf call with a call to fwrite in order to work around the apparent compiler optimization/rewrite failure that we are seeing with the new toolchain/iOS SDKs provided with Xcode6 and iOS8. * Fix ALL the header guards. * Createed a README.md with the LevelDB project description. * A new CONTRIBUTING file. * Don't implicitly convert uint64_t to size_t or int. Either preserve it as uint64_t, or explicitly cast. This fixes MSVC warnings about possible value truncation when compiling this code in Chromium. * Added a DumpFile() library function that encapsulates the guts of the "leveldbutil dump" command. This will allow clients to dump data to their log files instead of stdout. It will also allow clients to supply their own environment. * leveldb: Remove unused function 'ConsumeChar'. * leveldbutil: Remove unused member variables from WriteBatchItemPrinter. * OpenBSD, NetBSD and DragonflyBSD have _LITTLE_ENDIAN, so define PLATFORM_IS_LITTLE_ENDIAN like on FreeBSD. This fixes: * issue #143 * issue #198 * issue #249 * Switch from <cstdatomic> to <atomic>. The former never made it into the standard and doesn't exist in modern gcc versions at all. The later contains everything that leveldb was using from the former. This problem was noticed when porting to Portable Native Client where no memory barrier is defined. The fact that <cstdatomic> is missing normally goes unnoticed since memory barriers are defined for most architectures. * Make Hash() treat its input as unsigned. Before this change LevelDB files from platforms with different signedness of char were not compatible. This change fixes: issue #243 * Verify checksums of index/meta/filter blocks when paranoid_checks set. * Invoke all tools for iOS with xcrun. (This was causing problems with the new XCode 5.1.1 image on pulse.) * include <sys/stat.h> only once, and fix the following linter warning: "Found C system header after C++ system header" * When encountering a corrupted table file, return Status::Corruption instead of Status::InvalidArgument. * Support cygwin as build platform, patch is from https://code.google.com/p/leveldb/issues/detail?id=188 * Fix typo, merge patch from https://code.google.com/p/leveldb/issues/detail?id=159 * Fix typos and comments, and address the following two issues: * issue #166 * issue #241 * Add missing db synchronize after "fillseq" in the benchmark. * Removed unused variable in SeekRandom: value (issue #201)
10 years ago
Add Env::Remove{File,Dir} which obsolete Env::Delete{File,Dir}. The "DeleteFile" method name causes pain for Windows developers, because <windows.h> #defines a DeleteFile macro to DeleteFileW or DeleteFileA. Current code uses workarounds, like #undefining DeleteFile everywhere an Env is declared, implemented, or used. This CL removes the need for workarounds by renaming Env::DeleteFile to Env::RemoveFile. For consistency, Env::DeleteDir is also renamed to Env::RemoveDir. A few internal methods are also renamed for consistency. Software that supports Windows is expected to migrate any Env implementations and usage to Remove{File,Dir}, and never use the name Env::Delete{File,Dir} in its code. The renaming is done in a backwards-compatible way, at the risk of making it slightly more difficult to build a new correct Env implementation. The backwards compatibility is achieved using the following hacks: 1) Env::Remove{File,Dir} methods are added, with a default implementation that calls into Env::Delete{File,Dir}. This makes old Env implementations compatible with code that calls into the updated API. 2) The Env::Delete{File,Dir} methods are no longer pure virtuals. Instead, they gain a default implementation that calls into Env::Remove{File,Dir}. This makes updated Env implementations compatible with code that calls into the old API. The cost of this approach is that it's possible to write an Env without overriding either Rename{File,Dir} or Delete{File,Dir}, without getting a compiler warning. However, attempting to run the test suite will immediately fail with an infinite call stack ending in {Remove,Delete}{File,Dir}, making developers aware of the problem. PiperOrigin-RevId: 288710907
5 years ago
  1. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  4. #include <sys/types.h>
  5. #include <atomic>
  6. #include <cstdio>
  7. #include <cstdlib>
  8. #include "leveldb/cache.h"
  9. #include "leveldb/comparator.h"
  10. #include "leveldb/db.h"
  11. #include "leveldb/env.h"
  12. #include "leveldb/filter_policy.h"
  13. #include "leveldb/write_batch.h"
  14. #include "port/port.h"
  15. #include "util/crc32c.h"
  16. #include "util/histogram.h"
  17. #include "util/mutexlock.h"
  18. #include "util/random.h"
  19. #include "util/testutil.h"
  20. // Comma-separated list of operations to run in the specified order
  21. // Actual benchmarks:
  22. // fillseq -- write N values in sequential key order in async mode
  23. // fillrandom -- write N values in random key order in async mode
  24. // overwrite -- overwrite N values in random key order in async mode
  25. // fillsync -- write N/100 values in random key order in sync mode
  26. // fill100K -- write N/1000 100K values in random order in async mode
  27. // deleteseq -- delete N keys in sequential order
  28. // deleterandom -- delete N keys in random order
  29. // readseq -- read N times sequentially
  30. // readreverse -- read N times in reverse order
  31. // readrandom -- read N times in random order
  32. // readmissing -- read N missing keys in random order
  33. // readhot -- read N times in random order from 1% section of DB
  34. // seekrandom -- N random seeks
  35. // seekordered -- N ordered seeks
  36. // open -- cost of opening a DB
  37. // crc32c -- repeated crc32c of 4K of data
  38. // Meta operations:
  39. // compact -- Compact the entire DB
  40. // stats -- Print DB stats
  41. // sstables -- Print sstable info
  42. // heapprofile -- Dump a heap profile (if supported by this port)
  43. static const char* FLAGS_benchmarks =
  44. "fillseq,"
  45. "fillsync,"
  46. "fillrandom,"
  47. "overwrite,"
  48. "readrandom,"
  49. "readrandom," // Extra run to allow previous compactions to quiesce
  50. "readseq,"
  51. "readreverse,"
  52. "compact,"
  53. "readrandom,"
  54. "readseq,"
  55. "readreverse,"
  56. "fill100K,"
  57. "crc32c,"
  58. "snappycomp,"
  59. "snappyuncomp,";
  60. // Number of key/values to place in database
  61. static int FLAGS_num = 1000000;
  62. // Number of read operations to do. If negative, do FLAGS_num reads.
  63. static int FLAGS_reads = -1;
  64. // Number of concurrent threads to run.
  65. static int FLAGS_threads = 1;
  66. // Size of each value
  67. static int FLAGS_value_size = 100;
  68. // Arrange to generate values that shrink to this fraction of
  69. // their original size after compression
  70. static double FLAGS_compression_ratio = 0.5;
  71. // Print histogram of operation timings
  72. static bool FLAGS_histogram = false;
  73. // Count the number of string comparisons performed
  74. static bool FLAGS_comparisons = false;
  75. // Number of bytes to buffer in memtable before compacting
  76. // (initialized to default value by "main")
  77. static int FLAGS_write_buffer_size = 0;
  78. // Number of bytes written to each file.
  79. // (initialized to default value by "main")
  80. static int FLAGS_max_file_size = 0;
  81. // Approximate size of user data packed per block (before compression.
  82. // (initialized to default value by "main")
  83. static int FLAGS_block_size = 0;
  84. // Number of bytes to use as a cache of uncompressed data.
  85. // Negative means use default settings.
  86. static int FLAGS_cache_size = -1;
  87. // Maximum number of files to keep open at the same time (use default if == 0)
  88. static int FLAGS_open_files = 0;
  89. // Bloom filter bits per key.
  90. // Negative means use default settings.
  91. static int FLAGS_bloom_bits = -1;
  92. // Common key prefix length.
  93. static int FLAGS_key_prefix = 0;
  94. // If true, do not destroy the existing database. If you set this
  95. // flag and also specify a benchmark that wants a fresh database, that
  96. // benchmark will fail.
  97. static bool FLAGS_use_existing_db = false;
  98. // If true, reuse existing log/MANIFEST files when re-opening a database.
  99. static bool FLAGS_reuse_logs = false;
  100. // If true, use compression.
  101. static bool FLAGS_compression = true;
  102. // Use the db with the following name.
  103. static const char* FLAGS_db = nullptr;
  104. namespace leveldb {
  105. namespace {
  106. leveldb::Env* g_env = nullptr;
  107. class CountComparator : public Comparator {
  108. public:
  109. CountComparator(const Comparator* wrapped) : wrapped_(wrapped) {}
  110. ~CountComparator() override {}
  111. int Compare(const Slice& a, const Slice& b) const override {
  112. count_.fetch_add(1, std::memory_order_relaxed);
  113. return wrapped_->Compare(a, b);
  114. }
  115. const char* Name() const override { return wrapped_->Name(); }
  116. void FindShortestSeparator(std::string* start,
  117. const Slice& limit) const override {
  118. wrapped_->FindShortestSeparator(start, limit);
  119. }
  120. void FindShortSuccessor(std::string* key) const override {
  121. return wrapped_->FindShortSuccessor(key);
  122. }
  123. size_t comparisons() const { return count_.load(std::memory_order_relaxed); }
  124. void reset() { count_.store(0, std::memory_order_relaxed); }
  125. private:
  126. mutable std::atomic<size_t> count_{0};
  127. const Comparator* const wrapped_;
  128. };
  129. // Helper for quickly generating random data.
  130. class RandomGenerator {
  131. private:
  132. std::string data_;
  133. int pos_;
  134. public:
  135. RandomGenerator() {
  136. // We use a limited amount of data over and over again and ensure
  137. // that it is larger than the compression window (32KB), and also
  138. // large enough to serve all typical value sizes we want to write.
  139. Random rnd(301);
  140. std::string piece;
  141. while (data_.size() < 1048576) {
  142. // Add a short fragment that is as compressible as specified
  143. // by FLAGS_compression_ratio.
  144. test::CompressibleString(&rnd, FLAGS_compression_ratio, 100, &piece);
  145. data_.append(piece);
  146. }
  147. pos_ = 0;
  148. }
  149. Slice Generate(size_t len) {
  150. if (pos_ + len > data_.size()) {
  151. pos_ = 0;
  152. assert(len < data_.size());
  153. }
  154. pos_ += len;
  155. return Slice(data_.data() + pos_ - len, len);
  156. }
  157. };
  158. class KeyBuffer {
  159. public:
  160. KeyBuffer() {
  161. assert(FLAGS_key_prefix < sizeof(buffer_));
  162. memset(buffer_, 'a', FLAGS_key_prefix);
  163. }
  164. KeyBuffer& operator=(KeyBuffer& other) = delete;
  165. KeyBuffer(KeyBuffer& other) = delete;
  166. void Set(int k) {
  167. std::snprintf(buffer_ + FLAGS_key_prefix,
  168. sizeof(buffer_) - FLAGS_key_prefix, "%016d", k);
  169. }
  170. Slice slice() const { return Slice(buffer_, FLAGS_key_prefix + 16); }
  171. private:
  172. char buffer_[1024];
  173. };
  174. #if defined(__linux)
  175. static Slice TrimSpace(Slice s) {
  176. size_t start = 0;
  177. while (start < s.size() && isspace(s[start])) {
  178. start++;
  179. }
  180. size_t limit = s.size();
  181. while (limit > start && isspace(s[limit - 1])) {
  182. limit--;
  183. }
  184. return Slice(s.data() + start, limit - start);
  185. }
  186. #endif
  187. static void AppendWithSpace(std::string* str, Slice msg) {
  188. if (msg.empty()) return;
  189. if (!str->empty()) {
  190. str->push_back(' ');
  191. }
  192. str->append(msg.data(), msg.size());
  193. }
  194. class Stats {
  195. private:
  196. double start_;
  197. double finish_;
  198. double seconds_;
  199. int done_;
  200. int next_report_;
  201. int64_t bytes_;
  202. double last_op_finish_;
  203. Histogram hist_;
  204. std::string message_;
  205. public:
  206. Stats() { Start(); }
  207. void Start() {
  208. next_report_ = 100;
  209. hist_.Clear();
  210. done_ = 0;
  211. bytes_ = 0;
  212. seconds_ = 0;
  213. message_.clear();
  214. start_ = finish_ = last_op_finish_ = g_env->NowMicros();
  215. }
  216. void Merge(const Stats& other) {
  217. hist_.Merge(other.hist_);
  218. done_ += other.done_;
  219. bytes_ += other.bytes_;
  220. seconds_ += other.seconds_;
  221. if (other.start_ < start_) start_ = other.start_;
  222. if (other.finish_ > finish_) finish_ = other.finish_;
  223. // Just keep the messages from one thread
  224. if (message_.empty()) message_ = other.message_;
  225. }
  226. void Stop() {
  227. finish_ = g_env->NowMicros();
  228. seconds_ = (finish_ - start_) * 1e-6;
  229. }
  230. void AddMessage(Slice msg) { AppendWithSpace(&message_, msg); }
  231. void FinishedSingleOp() {
  232. if (FLAGS_histogram) {
  233. double now = g_env->NowMicros();
  234. double micros = now - last_op_finish_;
  235. hist_.Add(micros);
  236. if (micros > 20000) {
  237. std::fprintf(stderr, "long op: %.1f micros%30s\r", micros, "");
  238. std::fflush(stderr);
  239. }
  240. last_op_finish_ = now;
  241. }
  242. done_++;
  243. if (done_ >= next_report_) {
  244. if (next_report_ < 1000)
  245. next_report_ += 100;
  246. else if (next_report_ < 5000)
  247. next_report_ += 500;
  248. else if (next_report_ < 10000)
  249. next_report_ += 1000;
  250. else if (next_report_ < 50000)
  251. next_report_ += 5000;
  252. else if (next_report_ < 100000)
  253. next_report_ += 10000;
  254. else if (next_report_ < 500000)
  255. next_report_ += 50000;
  256. else
  257. next_report_ += 100000;
  258. std::fprintf(stderr, "... finished %d ops%30s\r", done_, "");
  259. std::fflush(stderr);
  260. }
  261. }
  262. void AddBytes(int64_t n) { bytes_ += n; }
  263. void Report(const Slice& name) {
  264. // Pretend at least one op was done in case we are running a benchmark
  265. // that does not call FinishedSingleOp().
  266. if (done_ < 1) done_ = 1;
  267. std::string extra;
  268. if (bytes_ > 0) {
  269. // Rate is computed on actual elapsed time, not the sum of per-thread
  270. // elapsed times.
  271. double elapsed = (finish_ - start_) * 1e-6;
  272. char rate[100];
  273. std::snprintf(rate, sizeof(rate), "%6.1f MB/s",
  274. (bytes_ / 1048576.0) / elapsed);
  275. extra = rate;
  276. }
  277. AppendWithSpace(&extra, message_);
  278. std::fprintf(stdout, "%-12s : %11.3f micros/op;%s%s\n",
  279. name.ToString().c_str(), seconds_ * 1e6 / done_,
  280. (extra.empty() ? "" : " "), extra.c_str());
  281. if (FLAGS_histogram) {
  282. std::fprintf(stdout, "Microseconds per op:\n%s\n",
  283. hist_.ToString().c_str());
  284. }
  285. std::fflush(stdout);
  286. }
  287. };
  288. // State shared by all concurrent executions of the same benchmark.
  289. struct SharedState {
  290. port::Mutex mu;
  291. port::CondVar cv GUARDED_BY(mu);
  292. int total GUARDED_BY(mu);
  293. // Each thread goes through the following states:
  294. // (1) initializing
  295. // (2) waiting for others to be initialized
  296. // (3) running
  297. // (4) done
  298. int num_initialized GUARDED_BY(mu);
  299. int num_done GUARDED_BY(mu);
  300. bool start GUARDED_BY(mu);
  301. SharedState(int total)
  302. : cv(&mu), total(total), num_initialized(0), num_done(0), start(false) {}
  303. };
  304. // Per-thread state for concurrent executions of the same benchmark.
  305. struct ThreadState {
  306. int tid; // 0..n-1 when running in n threads
  307. Random rand; // Has different seeds for different threads
  308. Stats stats;
  309. SharedState* shared;
  310. ThreadState(int index, int seed) : tid(index), rand(seed), shared(nullptr) {}
  311. };
  312. } // namespace
  313. class Benchmark {
  314. private:
  315. Cache* cache_;
  316. const FilterPolicy* filter_policy_;
  317. DB* db_;
  318. int num_;
  319. int value_size_;
  320. int entries_per_batch_;
  321. WriteOptions write_options_;
  322. int reads_;
  323. int heap_counter_;
  324. CountComparator count_comparator_;
  325. int total_thread_count_;
  326. void PrintHeader() {
  327. const int kKeySize = 16 + FLAGS_key_prefix;
  328. PrintEnvironment();
  329. std::fprintf(stdout, "Keys: %d bytes each\n", kKeySize);
  330. std::fprintf(
  331. stdout, "Values: %d bytes each (%d bytes after compression)\n",
  332. FLAGS_value_size,
  333. static_cast<int>(FLAGS_value_size * FLAGS_compression_ratio + 0.5));
  334. std::fprintf(stdout, "Entries: %d\n", num_);
  335. std::fprintf(stdout, "RawSize: %.1f MB (estimated)\n",
  336. ((static_cast<int64_t>(kKeySize + FLAGS_value_size) * num_) /
  337. 1048576.0));
  338. std::fprintf(
  339. stdout, "FileSize: %.1f MB (estimated)\n",
  340. (((kKeySize + FLAGS_value_size * FLAGS_compression_ratio) * num_) /
  341. 1048576.0));
  342. PrintWarnings();
  343. std::fprintf(stdout, "------------------------------------------------\n");
  344. }
  345. void PrintWarnings() {
  346. #if defined(__GNUC__) && !defined(__OPTIMIZE__)
  347. std::fprintf(
  348. stdout,
  349. "WARNING: Optimization is disabled: benchmarks unnecessarily slow\n");
  350. #endif
  351. #ifndef NDEBUG
  352. std::fprintf(
  353. stdout,
  354. "WARNING: Assertions are enabled; benchmarks unnecessarily slow\n");
  355. #endif
  356. // See if snappy is working by attempting to compress a compressible string
  357. const char text[] = "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy";
  358. std::string compressed;
  359. if (!port::Snappy_Compress(text, sizeof(text), &compressed)) {
  360. std::fprintf(stdout, "WARNING: Snappy compression is not enabled\n");
  361. } else if (compressed.size() >= sizeof(text)) {
  362. std::fprintf(stdout, "WARNING: Snappy compression is not effective\n");
  363. }
  364. }
  365. void PrintEnvironment() {
  366. std::fprintf(stderr, "LevelDB: version %d.%d\n", kMajorVersion,
  367. kMinorVersion);
  368. #if defined(__linux)
  369. time_t now = time(nullptr);
  370. std::fprintf(stderr, "Date: %s",
  371. ctime(&now)); // ctime() adds newline
  372. FILE* cpuinfo = std::fopen("/proc/cpuinfo", "r");
  373. if (cpuinfo != nullptr) {
  374. char line[1000];
  375. int num_cpus = 0;
  376. std::string cpu_type;
  377. std::string cache_size;
  378. while (fgets(line, sizeof(line), cpuinfo) != nullptr) {
  379. const char* sep = strchr(line, ':');
  380. if (sep == nullptr) {
  381. continue;
  382. }
  383. Slice key = TrimSpace(Slice(line, sep - 1 - line));
  384. Slice val = TrimSpace(Slice(sep + 1));
  385. if (key == "model name") {
  386. ++num_cpus;
  387. cpu_type = val.ToString();
  388. } else if (key == "cache size") {
  389. cache_size = val.ToString();
  390. }
  391. }
  392. std::fclose(cpuinfo);
  393. std::fprintf(stderr, "CPU: %d * %s\n", num_cpus, cpu_type.c_str());
  394. std::fprintf(stderr, "CPUCache: %s\n", cache_size.c_str());
  395. }
  396. #endif
  397. }
  398. public:
  399. Benchmark()
  400. : cache_(FLAGS_cache_size >= 0 ? NewLRUCache(FLAGS_cache_size) : nullptr),
  401. filter_policy_(FLAGS_bloom_bits >= 0
  402. ? NewBloomFilterPolicy(FLAGS_bloom_bits)
  403. : nullptr),
  404. db_(nullptr),
  405. num_(FLAGS_num),
  406. value_size_(FLAGS_value_size),
  407. entries_per_batch_(1),
  408. reads_(FLAGS_reads < 0 ? FLAGS_num : FLAGS_reads),
  409. heap_counter_(0),
  410. count_comparator_(BytewiseComparator()),
  411. total_thread_count_(0) {
  412. std::vector<std::string> files;
  413. g_env->GetChildren(FLAGS_db, &files);
  414. for (size_t i = 0; i < files.size(); i++) {
  415. if (Slice(files[i]).starts_with("heap-")) {
  416. g_env->RemoveFile(std::string(FLAGS_db) + "/" + files[i]);
  417. }
  418. }
  419. if (!FLAGS_use_existing_db) {
  420. DestroyDB(FLAGS_db, Options());
  421. }
  422. }
  423. ~Benchmark() {
  424. delete db_;
  425. delete cache_;
  426. delete filter_policy_;
  427. }
  428. void Run() {
  429. PrintHeader();
  430. Open();
  431. const char* benchmarks = FLAGS_benchmarks;
  432. while (benchmarks != nullptr) {
  433. const char* sep = strchr(benchmarks, ',');
  434. Slice name;
  435. if (sep == nullptr) {
  436. name = benchmarks;
  437. benchmarks = nullptr;
  438. } else {
  439. name = Slice(benchmarks, sep - benchmarks);
  440. benchmarks = sep + 1;
  441. }
  442. // Reset parameters that may be overridden below
  443. num_ = FLAGS_num;
  444. reads_ = (FLAGS_reads < 0 ? FLAGS_num : FLAGS_reads);
  445. value_size_ = FLAGS_value_size;
  446. entries_per_batch_ = 1;
  447. write_options_ = WriteOptions();
  448. void (Benchmark::*method)(ThreadState*) = nullptr;
  449. bool fresh_db = false;
  450. int num_threads = FLAGS_threads;
  451. if (name == Slice("open")) {
  452. method = &Benchmark::OpenBench;
  453. num_ /= 10000;
  454. if (num_ < 1) num_ = 1;
  455. } else if (name == Slice("fillseq")) {
  456. fresh_db = true;
  457. method = &Benchmark::WriteSeq;
  458. } else if (name == Slice("fillbatch")) {
  459. fresh_db = true;
  460. entries_per_batch_ = 1000;
  461. method = &Benchmark::WriteSeq;
  462. } else if (name == Slice("fillrandom")) {
  463. fresh_db = true;
  464. method = &Benchmark::WriteRandom;
  465. } else if (name == Slice("overwrite")) {
  466. fresh_db = false;
  467. method = &Benchmark::WriteRandom;
  468. } else if (name == Slice("fillsync")) {
  469. fresh_db = true;
  470. num_ /= 1000;
  471. write_options_.sync = true;
  472. method = &Benchmark::WriteRandom;
  473. } else if (name == Slice("fill100K")) {
  474. fresh_db = true;
  475. num_ /= 1000;
  476. value_size_ = 100 * 1000;
  477. method = &Benchmark::WriteRandom;
  478. } else if (name == Slice("readseq")) {
  479. method = &Benchmark::ReadSequential;
  480. } else if (name == Slice("readreverse")) {
  481. method = &Benchmark::ReadReverse;
  482. } else if (name == Slice("readrandom")) {
  483. method = &Benchmark::ReadRandom;
  484. } else if (name == Slice("readmissing")) {
  485. method = &Benchmark::ReadMissing;
  486. } else if (name == Slice("seekrandom")) {
  487. method = &Benchmark::SeekRandom;
  488. } else if (name == Slice("seekordered")) {
  489. method = &Benchmark::SeekOrdered;
  490. } else if (name == Slice("readhot")) {
  491. method = &Benchmark::ReadHot;
  492. } else if (name == Slice("readrandomsmall")) {
  493. reads_ /= 1000;
  494. method = &Benchmark::ReadRandom;
  495. } else if (name == Slice("deleteseq")) {
  496. method = &Benchmark::DeleteSeq;
  497. } else if (name == Slice("deleterandom")) {
  498. method = &Benchmark::DeleteRandom;
  499. } else if (name == Slice("readwhilewriting")) {
  500. num_threads++; // Add extra thread for writing
  501. method = &Benchmark::ReadWhileWriting;
  502. } else if (name == Slice("compact")) {
  503. method = &Benchmark::Compact;
  504. } else if (name == Slice("crc32c")) {
  505. method = &Benchmark::Crc32c;
  506. } else if (name == Slice("snappycomp")) {
  507. method = &Benchmark::SnappyCompress;
  508. } else if (name == Slice("snappyuncomp")) {
  509. method = &Benchmark::SnappyUncompress;
  510. } else if (name == Slice("heapprofile")) {
  511. HeapProfile();
  512. } else if (name == Slice("stats")) {
  513. PrintStats("leveldb.stats");
  514. } else if (name == Slice("sstables")) {
  515. PrintStats("leveldb.sstables");
  516. } else {
  517. if (!name.empty()) { // No error message for empty name
  518. std::fprintf(stderr, "unknown benchmark '%s'\n",
  519. name.ToString().c_str());
  520. }
  521. }
  522. if (fresh_db) {
  523. if (FLAGS_use_existing_db) {
  524. std::fprintf(stdout, "%-12s : skipped (--use_existing_db is true)\n",
  525. name.ToString().c_str());
  526. method = nullptr;
  527. } else {
  528. delete db_;
  529. db_ = nullptr;
  530. DestroyDB(FLAGS_db, Options());
  531. Open();
  532. }
  533. }
  534. if (method != nullptr) {
  535. RunBenchmark(num_threads, name, method);
  536. }
  537. }
  538. }
  539. private:
  540. struct ThreadArg {
  541. Benchmark* bm;
  542. SharedState* shared;
  543. ThreadState* thread;
  544. void (Benchmark::*method)(ThreadState*);
  545. };
  546. static void ThreadBody(void* v) {
  547. ThreadArg* arg = reinterpret_cast<ThreadArg*>(v);
  548. SharedState* shared = arg->shared;
  549. ThreadState* thread = arg->thread;
  550. {
  551. MutexLock l(&shared->mu);
  552. shared->num_initialized++;
  553. if (shared->num_initialized >= shared->total) {
  554. shared->cv.SignalAll();
  555. }
  556. while (!shared->start) {
  557. shared->cv.Wait();
  558. }
  559. }
  560. thread->stats.Start();
  561. (arg->bm->*(arg->method))(thread);
  562. thread->stats.Stop();
  563. {
  564. MutexLock l(&shared->mu);
  565. shared->num_done++;
  566. if (shared->num_done >= shared->total) {
  567. shared->cv.SignalAll();
  568. }
  569. }
  570. }
  571. void RunBenchmark(int n, Slice name,
  572. void (Benchmark::*method)(ThreadState*)) {
  573. SharedState shared(n);
  574. ThreadArg* arg = new ThreadArg[n];
  575. for (int i = 0; i < n; i++) {
  576. arg[i].bm = this;
  577. arg[i].method = method;
  578. arg[i].shared = &shared;
  579. ++total_thread_count_;
  580. // Seed the thread's random state deterministically based upon thread
  581. // creation across all benchmarks. This ensures that the seeds are unique
  582. // but reproducible when rerunning the same set of benchmarks.
  583. arg[i].thread = new ThreadState(i, /*seed=*/1000 + total_thread_count_);
  584. arg[i].thread->shared = &shared;
  585. g_env->StartThread(ThreadBody, &arg[i]);
  586. }
  587. shared.mu.Lock();
  588. while (shared.num_initialized < n) {
  589. shared.cv.Wait();
  590. }
  591. shared.start = true;
  592. shared.cv.SignalAll();
  593. while (shared.num_done < n) {
  594. shared.cv.Wait();
  595. }
  596. shared.mu.Unlock();
  597. for (int i = 1; i < n; i++) {
  598. arg[0].thread->stats.Merge(arg[i].thread->stats);
  599. }
  600. arg[0].thread->stats.Report(name);
  601. if (FLAGS_comparisons) {
  602. fprintf(stdout, "Comparisons: %zu\n", count_comparator_.comparisons());
  603. count_comparator_.reset();
  604. fflush(stdout);
  605. }
  606. for (int i = 0; i < n; i++) {
  607. delete arg[i].thread;
  608. }
  609. delete[] arg;
  610. }
  611. void Crc32c(ThreadState* thread) {
  612. // Checksum about 500MB of data total
  613. const int size = 4096;
  614. const char* label = "(4K per op)";
  615. std::string data(size, 'x');
  616. int64_t bytes = 0;
  617. uint32_t crc = 0;
  618. while (bytes < 500 * 1048576) {
  619. crc = crc32c::Value(data.data(), size);
  620. thread->stats.FinishedSingleOp();
  621. bytes += size;
  622. }
  623. // Print so result is not dead
  624. std::fprintf(stderr, "... crc=0x%x\r", static_cast<unsigned int>(crc));
  625. thread->stats.AddBytes(bytes);
  626. thread->stats.AddMessage(label);
  627. }
  628. void SnappyCompress(ThreadState* thread) {
  629. RandomGenerator gen;
  630. Slice input = gen.Generate(Options().block_size);
  631. int64_t bytes = 0;
  632. int64_t produced = 0;
  633. bool ok = true;
  634. std::string compressed;
  635. while (ok && bytes < 1024 * 1048576) { // Compress 1G
  636. ok = port::Snappy_Compress(input.data(), input.size(), &compressed);
  637. produced += compressed.size();
  638. bytes += input.size();
  639. thread->stats.FinishedSingleOp();
  640. }
  641. if (!ok) {
  642. thread->stats.AddMessage("(snappy failure)");
  643. } else {
  644. char buf[100];
  645. std::snprintf(buf, sizeof(buf), "(output: %.1f%%)",
  646. (produced * 100.0) / bytes);
  647. thread->stats.AddMessage(buf);
  648. thread->stats.AddBytes(bytes);
  649. }
  650. }
  651. void SnappyUncompress(ThreadState* thread) {
  652. RandomGenerator gen;
  653. Slice input = gen.Generate(Options().block_size);
  654. std::string compressed;
  655. bool ok = port::Snappy_Compress(input.data(), input.size(), &compressed);
  656. int64_t bytes = 0;
  657. char* uncompressed = new char[input.size()];
  658. while (ok && bytes < 1024 * 1048576) { // Compress 1G
  659. ok = port::Snappy_Uncompress(compressed.data(), compressed.size(),
  660. uncompressed);
  661. bytes += input.size();
  662. thread->stats.FinishedSingleOp();
  663. }
  664. delete[] uncompressed;
  665. if (!ok) {
  666. thread->stats.AddMessage("(snappy failure)");
  667. } else {
  668. thread->stats.AddBytes(bytes);
  669. }
  670. }
  671. void Open() {
  672. assert(db_ == nullptr);
  673. Options options;
  674. options.env = g_env;
  675. options.create_if_missing = !FLAGS_use_existing_db;
  676. options.block_cache = cache_;
  677. options.write_buffer_size = FLAGS_write_buffer_size;
  678. options.max_file_size = FLAGS_max_file_size;
  679. options.block_size = FLAGS_block_size;
  680. if (FLAGS_comparisons) {
  681. options.comparator = &count_comparator_;
  682. }
  683. options.max_open_files = FLAGS_open_files;
  684. options.filter_policy = filter_policy_;
  685. options.reuse_logs = FLAGS_reuse_logs;
  686. options.compression =
  687. FLAGS_compression ? kSnappyCompression : kNoCompression;
  688. Status s = DB::Open(options, FLAGS_db, &db_);
  689. if (!s.ok()) {
  690. std::fprintf(stderr, "open error: %s\n", s.ToString().c_str());
  691. std::exit(1);
  692. }
  693. }
  694. void OpenBench(ThreadState* thread) {
  695. for (int i = 0; i < num_; i++) {
  696. delete db_;
  697. Open();
  698. thread->stats.FinishedSingleOp();
  699. }
  700. }
  701. void WriteSeq(ThreadState* thread) { DoWrite(thread, true); }
  702. void WriteRandom(ThreadState* thread) { DoWrite(thread, false); }
  703. void DoWrite(ThreadState* thread, bool seq) {
  704. if (num_ != FLAGS_num) {
  705. char msg[100];
  706. std::snprintf(msg, sizeof(msg), "(%d ops)", num_);
  707. thread->stats.AddMessage(msg);
  708. }
  709. RandomGenerator gen;
  710. WriteBatch batch;
  711. Status s;
  712. int64_t bytes = 0;
  713. KeyBuffer key;
  714. for (int i = 0; i < num_; i += entries_per_batch_) {
  715. batch.Clear();
  716. for (int j = 0; j < entries_per_batch_; j++) {
  717. const int k = seq ? i + j : thread->rand.Uniform(FLAGS_num);
  718. key.Set(k);
  719. batch.Put(key.slice(), gen.Generate(value_size_));
  720. bytes += value_size_ + key.slice().size();
  721. thread->stats.FinishedSingleOp();
  722. }
  723. s = db_->Write(write_options_, &batch);
  724. if (!s.ok()) {
  725. std::fprintf(stderr, "put error: %s\n", s.ToString().c_str());
  726. std::exit(1);
  727. }
  728. }
  729. thread->stats.AddBytes(bytes);
  730. }
  731. void ReadSequential(ThreadState* thread) {
  732. Iterator* iter = db_->NewIterator(ReadOptions());
  733. int i = 0;
  734. int64_t bytes = 0;
  735. for (iter->SeekToFirst(); i < reads_ && iter->Valid(); iter->Next()) {
  736. bytes += iter->key().size() + iter->value().size();
  737. thread->stats.FinishedSingleOp();
  738. ++i;
  739. }
  740. delete iter;
  741. thread->stats.AddBytes(bytes);
  742. }
  743. void ReadReverse(ThreadState* thread) {
  744. Iterator* iter = db_->NewIterator(ReadOptions());
  745. int i = 0;
  746. int64_t bytes = 0;
  747. for (iter->SeekToLast(); i < reads_ && iter->Valid(); iter->Prev()) {
  748. bytes += iter->key().size() + iter->value().size();
  749. thread->stats.FinishedSingleOp();
  750. ++i;
  751. }
  752. delete iter;
  753. thread->stats.AddBytes(bytes);
  754. }
  755. void ReadRandom(ThreadState* thread) {
  756. ReadOptions options;
  757. std::string value;
  758. int found = 0;
  759. KeyBuffer key;
  760. for (int i = 0; i < reads_; i++) {
  761. const int k = thread->rand.Uniform(FLAGS_num);
  762. key.Set(k);
  763. if (db_->Get(options, key.slice(), &value).ok()) {
  764. found++;
  765. }
  766. thread->stats.FinishedSingleOp();
  767. }
  768. char msg[100];
  769. std::snprintf(msg, sizeof(msg), "(%d of %d found)", found, num_);
  770. thread->stats.AddMessage(msg);
  771. }
  772. void ReadMissing(ThreadState* thread) {
  773. ReadOptions options;
  774. std::string value;
  775. KeyBuffer key;
  776. for (int i = 0; i < reads_; i++) {
  777. const int k = thread->rand.Uniform(FLAGS_num);
  778. key.Set(k);
  779. Slice s = Slice(key.slice().data(), key.slice().size() - 1);
  780. db_->Get(options, s, &value);
  781. thread->stats.FinishedSingleOp();
  782. }
  783. }
  784. void ReadHot(ThreadState* thread) {
  785. ReadOptions options;
  786. std::string value;
  787. const int range = (FLAGS_num + 99) / 100;
  788. KeyBuffer key;
  789. for (int i = 0; i < reads_; i++) {
  790. const int k = thread->rand.Uniform(range);
  791. key.Set(k);
  792. db_->Get(options, key.slice(), &value);
  793. thread->stats.FinishedSingleOp();
  794. }
  795. }
  796. void SeekRandom(ThreadState* thread) {
  797. ReadOptions options;
  798. int found = 0;
  799. KeyBuffer key;
  800. for (int i = 0; i < reads_; i++) {
  801. Iterator* iter = db_->NewIterator(options);
  802. const int k = thread->rand.Uniform(FLAGS_num);
  803. key.Set(k);
  804. iter->Seek(key.slice());
  805. if (iter->Valid() && iter->key() == key.slice()) found++;
  806. delete iter;
  807. thread->stats.FinishedSingleOp();
  808. }
  809. char msg[100];
  810. snprintf(msg, sizeof(msg), "(%d of %d found)", found, num_);
  811. thread->stats.AddMessage(msg);
  812. }
  813. void SeekOrdered(ThreadState* thread) {
  814. ReadOptions options;
  815. Iterator* iter = db_->NewIterator(options);
  816. int found = 0;
  817. int k = 0;
  818. KeyBuffer key;
  819. for (int i = 0; i < reads_; i++) {
  820. k = (k + (thread->rand.Uniform(100))) % FLAGS_num;
  821. key.Set(k);
  822. iter->Seek(key.slice());
  823. if (iter->Valid() && iter->key() == key.slice()) found++;
  824. thread->stats.FinishedSingleOp();
  825. }
  826. delete iter;
  827. char msg[100];
  828. std::snprintf(msg, sizeof(msg), "(%d of %d found)", found, num_);
  829. thread->stats.AddMessage(msg);
  830. }
  831. void DoDelete(ThreadState* thread, bool seq) {
  832. RandomGenerator gen;
  833. WriteBatch batch;
  834. Status s;
  835. KeyBuffer key;
  836. for (int i = 0; i < num_; i += entries_per_batch_) {
  837. batch.Clear();
  838. for (int j = 0; j < entries_per_batch_; j++) {
  839. const int k = seq ? i + j : (thread->rand.Uniform(FLAGS_num));
  840. key.Set(k);
  841. batch.Delete(key.slice());
  842. thread->stats.FinishedSingleOp();
  843. }
  844. s = db_->Write(write_options_, &batch);
  845. if (!s.ok()) {
  846. std::fprintf(stderr, "del error: %s\n", s.ToString().c_str());
  847. std::exit(1);
  848. }
  849. }
  850. }
  851. void DeleteSeq(ThreadState* thread) { DoDelete(thread, true); }
  852. void DeleteRandom(ThreadState* thread) { DoDelete(thread, false); }
  853. void ReadWhileWriting(ThreadState* thread) {
  854. if (thread->tid > 0) {
  855. ReadRandom(thread);
  856. } else {
  857. // Special thread that keeps writing until other threads are done.
  858. RandomGenerator gen;
  859. KeyBuffer key;
  860. while (true) {
  861. {
  862. MutexLock l(&thread->shared->mu);
  863. if (thread->shared->num_done + 1 >= thread->shared->num_initialized) {
  864. // Other threads have finished
  865. break;
  866. }
  867. }
  868. const int k = thread->rand.Uniform(FLAGS_num);
  869. key.Set(k);
  870. Status s =
  871. db_->Put(write_options_, key.slice(), gen.Generate(value_size_));
  872. if (!s.ok()) {
  873. std::fprintf(stderr, "put error: %s\n", s.ToString().c_str());
  874. std::exit(1);
  875. }
  876. }
  877. // Do not count any of the preceding work/delay in stats.
  878. thread->stats.Start();
  879. }
  880. }
  881. void Compact(ThreadState* thread) { db_->CompactRange(nullptr, nullptr); }
  882. void PrintStats(const char* key) {
  883. std::string stats;
  884. if (!db_->GetProperty(key, &stats)) {
  885. stats = "(failed)";
  886. }
  887. std::fprintf(stdout, "\n%s\n", stats.c_str());
  888. }
  889. static void WriteToFile(void* arg, const char* buf, int n) {
  890. reinterpret_cast<WritableFile*>(arg)->Append(Slice(buf, n));
  891. }
  892. void HeapProfile() {
  893. char fname[100];
  894. std::snprintf(fname, sizeof(fname), "%s/heap-%04d", FLAGS_db,
  895. ++heap_counter_);
  896. WritableFile* file;
  897. Status s = g_env->NewWritableFile(fname, &file);
  898. if (!s.ok()) {
  899. std::fprintf(stderr, "%s\n", s.ToString().c_str());
  900. return;
  901. }
  902. bool ok = port::GetHeapProfile(WriteToFile, file);
  903. delete file;
  904. if (!ok) {
  905. std::fprintf(stderr, "heap profiling not supported\n");
  906. g_env->RemoveFile(fname);
  907. }
  908. }
  909. };
  910. } // namespace leveldb
  911. int main(int argc, char** argv) {
  912. FLAGS_write_buffer_size = leveldb::Options().write_buffer_size;
  913. FLAGS_max_file_size = leveldb::Options().max_file_size;
  914. FLAGS_block_size = leveldb::Options().block_size;
  915. FLAGS_open_files = leveldb::Options().max_open_files;
  916. std::string default_db_path;
  917. for (int i = 1; i < argc; i++) {
  918. double d;
  919. int n;
  920. char junk;
  921. if (leveldb::Slice(argv[i]).starts_with("--benchmarks=")) {
  922. FLAGS_benchmarks = argv[i] + strlen("--benchmarks=");
  923. } else if (sscanf(argv[i], "--compression_ratio=%lf%c", &d, &junk) == 1) {
  924. FLAGS_compression_ratio = d;
  925. } else if (sscanf(argv[i], "--histogram=%d%c", &n, &junk) == 1 &&
  926. (n == 0 || n == 1)) {
  927. FLAGS_histogram = n;
  928. } else if (sscanf(argv[i], "--comparisons=%d%c", &n, &junk) == 1 &&
  929. (n == 0 || n == 1)) {
  930. FLAGS_comparisons = n;
  931. } else if (sscanf(argv[i], "--use_existing_db=%d%c", &n, &junk) == 1 &&
  932. (n == 0 || n == 1)) {
  933. FLAGS_use_existing_db = n;
  934. } else if (sscanf(argv[i], "--reuse_logs=%d%c", &n, &junk) == 1 &&
  935. (n == 0 || n == 1)) {
  936. FLAGS_reuse_logs = n;
  937. } else if (sscanf(argv[i], "--compression=%d%c", &n, &junk) == 1 &&
  938. (n == 0 || n == 1)) {
  939. FLAGS_compression = n;
  940. } else if (sscanf(argv[i], "--num=%d%c", &n, &junk) == 1) {
  941. FLAGS_num = n;
  942. } else if (sscanf(argv[i], "--reads=%d%c", &n, &junk) == 1) {
  943. FLAGS_reads = n;
  944. } else if (sscanf(argv[i], "--threads=%d%c", &n, &junk) == 1) {
  945. FLAGS_threads = n;
  946. } else if (sscanf(argv[i], "--value_size=%d%c", &n, &junk) == 1) {
  947. FLAGS_value_size = n;
  948. } else if (sscanf(argv[i], "--write_buffer_size=%d%c", &n, &junk) == 1) {
  949. FLAGS_write_buffer_size = n;
  950. } else if (sscanf(argv[i], "--max_file_size=%d%c", &n, &junk) == 1) {
  951. FLAGS_max_file_size = n;
  952. } else if (sscanf(argv[i], "--block_size=%d%c", &n, &junk) == 1) {
  953. FLAGS_block_size = n;
  954. } else if (sscanf(argv[i], "--key_prefix=%d%c", &n, &junk) == 1) {
  955. FLAGS_key_prefix = n;
  956. } else if (sscanf(argv[i], "--cache_size=%d%c", &n, &junk) == 1) {
  957. FLAGS_cache_size = n;
  958. } else if (sscanf(argv[i], "--bloom_bits=%d%c", &n, &junk) == 1) {
  959. FLAGS_bloom_bits = n;
  960. } else if (sscanf(argv[i], "--open_files=%d%c", &n, &junk) == 1) {
  961. FLAGS_open_files = n;
  962. } else if (strncmp(argv[i], "--db=", 5) == 0) {
  963. FLAGS_db = argv[i] + 5;
  964. } else {
  965. std::fprintf(stderr, "Invalid flag '%s'\n", argv[i]);
  966. std::exit(1);
  967. }
  968. }
  969. leveldb::g_env = leveldb::Env::Default();
  970. // Choose a location for the test database if none given with --db=<path>
  971. if (FLAGS_db == nullptr) {
  972. leveldb::g_env->GetTestDirectory(&default_db_path);
  973. default_db_path += "/dbbench";
  974. FLAGS_db = default_db_path.c_str();
  975. }
  976. leveldb::Benchmark benchmark;
  977. benchmark.Run();
  978. return 0;
  979. }