小组成员:10215300402-朱维清 & 10222140408 谷杰
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1090 строки
32 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
4 лет назад
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 лет назад
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
4 лет назад
  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. // Use the db with the following name.
  101. static const char* FLAGS_db = nullptr;
  102. namespace leveldb {
  103. namespace {
  104. leveldb::Env* g_env = nullptr;
  105. class CountComparator : public Comparator {
  106. public:
  107. CountComparator(const Comparator* wrapped) : wrapped_(wrapped) {}
  108. ~CountComparator() override {}
  109. int Compare(const Slice& a, const Slice& b) const override {
  110. count_.fetch_add(1, std::memory_order_relaxed);
  111. return wrapped_->Compare(a, b);
  112. }
  113. const char* Name() const override { return wrapped_->Name(); }
  114. void FindShortestSeparator(std::string* start,
  115. const Slice& limit) const override {
  116. wrapped_->FindShortestSeparator(start, limit);
  117. }
  118. void FindShortSuccessor(std::string* key) const override {
  119. return wrapped_->FindShortSuccessor(key);
  120. }
  121. size_t comparisons() const { return count_.load(std::memory_order_relaxed); }
  122. void reset() { count_.store(0, std::memory_order_relaxed); }
  123. private:
  124. mutable std::atomic<size_t> count_{0};
  125. const Comparator* const wrapped_;
  126. };
  127. // Helper for quickly generating random data.
  128. class RandomGenerator {
  129. private:
  130. std::string data_;
  131. int pos_;
  132. public:
  133. RandomGenerator() {
  134. // We use a limited amount of data over and over again and ensure
  135. // that it is larger than the compression window (32KB), and also
  136. // large enough to serve all typical value sizes we want to write.
  137. Random rnd(301);
  138. std::string piece;
  139. while (data_.size() < 1048576) {
  140. // Add a short fragment that is as compressible as specified
  141. // by FLAGS_compression_ratio.
  142. test::CompressibleString(&rnd, FLAGS_compression_ratio, 100, &piece);
  143. data_.append(piece);
  144. }
  145. pos_ = 0;
  146. }
  147. Slice Generate(size_t len) {
  148. if (pos_ + len > data_.size()) {
  149. pos_ = 0;
  150. assert(len < data_.size());
  151. }
  152. pos_ += len;
  153. return Slice(data_.data() + pos_ - len, len);
  154. }
  155. };
  156. class KeyBuffer {
  157. public:
  158. KeyBuffer() {
  159. assert(FLAGS_key_prefix < sizeof(buffer_));
  160. memset(buffer_, 'a', FLAGS_key_prefix);
  161. }
  162. KeyBuffer& operator=(KeyBuffer& other) = delete;
  163. KeyBuffer(KeyBuffer& other) = delete;
  164. void Set(int k) {
  165. std::snprintf(buffer_ + FLAGS_key_prefix,
  166. sizeof(buffer_) - FLAGS_key_prefix, "%016d", k);
  167. }
  168. Slice slice() const { return Slice(buffer_, FLAGS_key_prefix + 16); }
  169. private:
  170. char buffer_[1024];
  171. };
  172. #if defined(__linux)
  173. static Slice TrimSpace(Slice s) {
  174. size_t start = 0;
  175. while (start < s.size() && isspace(s[start])) {
  176. start++;
  177. }
  178. size_t limit = s.size();
  179. while (limit > start && isspace(s[limit - 1])) {
  180. limit--;
  181. }
  182. return Slice(s.data() + start, limit - start);
  183. }
  184. #endif
  185. static void AppendWithSpace(std::string* str, Slice msg) {
  186. if (msg.empty()) return;
  187. if (!str->empty()) {
  188. str->push_back(' ');
  189. }
  190. str->append(msg.data(), msg.size());
  191. }
  192. class Stats {
  193. private:
  194. double start_;
  195. double finish_;
  196. double seconds_;
  197. int done_;
  198. int next_report_;
  199. int64_t bytes_;
  200. double last_op_finish_;
  201. Histogram hist_;
  202. std::string message_;
  203. public:
  204. Stats() { Start(); }
  205. void Start() {
  206. next_report_ = 100;
  207. hist_.Clear();
  208. done_ = 0;
  209. bytes_ = 0;
  210. seconds_ = 0;
  211. message_.clear();
  212. start_ = finish_ = last_op_finish_ = g_env->NowMicros();
  213. }
  214. void Merge(const Stats& other) {
  215. hist_.Merge(other.hist_);
  216. done_ += other.done_;
  217. bytes_ += other.bytes_;
  218. seconds_ += other.seconds_;
  219. if (other.start_ < start_) start_ = other.start_;
  220. if (other.finish_ > finish_) finish_ = other.finish_;
  221. // Just keep the messages from one thread
  222. if (message_.empty()) message_ = other.message_;
  223. }
  224. void Stop() {
  225. finish_ = g_env->NowMicros();
  226. seconds_ = (finish_ - start_) * 1e-6;
  227. }
  228. void AddMessage(Slice msg) { AppendWithSpace(&message_, msg); }
  229. void FinishedSingleOp() {
  230. if (FLAGS_histogram) {
  231. double now = g_env->NowMicros();
  232. double micros = now - last_op_finish_;
  233. hist_.Add(micros);
  234. if (micros > 20000) {
  235. std::fprintf(stderr, "long op: %.1f micros%30s\r", micros, "");
  236. std::fflush(stderr);
  237. }
  238. last_op_finish_ = now;
  239. }
  240. done_++;
  241. if (done_ >= next_report_) {
  242. if (next_report_ < 1000)
  243. next_report_ += 100;
  244. else if (next_report_ < 5000)
  245. next_report_ += 500;
  246. else if (next_report_ < 10000)
  247. next_report_ += 1000;
  248. else if (next_report_ < 50000)
  249. next_report_ += 5000;
  250. else if (next_report_ < 100000)
  251. next_report_ += 10000;
  252. else if (next_report_ < 500000)
  253. next_report_ += 50000;
  254. else
  255. next_report_ += 100000;
  256. std::fprintf(stderr, "... finished %d ops%30s\r", done_, "");
  257. std::fflush(stderr);
  258. }
  259. }
  260. void AddBytes(int64_t n) { bytes_ += n; }
  261. void Report(const Slice& name) {
  262. // Pretend at least one op was done in case we are running a benchmark
  263. // that does not call FinishedSingleOp().
  264. if (done_ < 1) done_ = 1;
  265. std::string extra;
  266. if (bytes_ > 0) {
  267. // Rate is computed on actual elapsed time, not the sum of per-thread
  268. // elapsed times.
  269. double elapsed = (finish_ - start_) * 1e-6;
  270. char rate[100];
  271. std::snprintf(rate, sizeof(rate), "%6.1f MB/s",
  272. (bytes_ / 1048576.0) / elapsed);
  273. extra = rate;
  274. }
  275. AppendWithSpace(&extra, message_);
  276. std::fprintf(stdout, "%-12s : %11.3f micros/op;%s%s\n",
  277. name.ToString().c_str(), seconds_ * 1e6 / done_,
  278. (extra.empty() ? "" : " "), extra.c_str());
  279. if (FLAGS_histogram) {
  280. std::fprintf(stdout, "Microseconds per op:\n%s\n",
  281. hist_.ToString().c_str());
  282. }
  283. std::fflush(stdout);
  284. }
  285. };
  286. // State shared by all concurrent executions of the same benchmark.
  287. struct SharedState {
  288. port::Mutex mu;
  289. port::CondVar cv GUARDED_BY(mu);
  290. int total GUARDED_BY(mu);
  291. // Each thread goes through the following states:
  292. // (1) initializing
  293. // (2) waiting for others to be initialized
  294. // (3) running
  295. // (4) done
  296. int num_initialized GUARDED_BY(mu);
  297. int num_done GUARDED_BY(mu);
  298. bool start GUARDED_BY(mu);
  299. SharedState(int total)
  300. : cv(&mu), total(total), num_initialized(0), num_done(0), start(false) {}
  301. };
  302. // Per-thread state for concurrent executions of the same benchmark.
  303. struct ThreadState {
  304. int tid; // 0..n-1 when running in n threads
  305. Random rand; // Has different seeds for different threads
  306. Stats stats;
  307. SharedState* shared;
  308. ThreadState(int index, int seed) : tid(index), rand(seed), shared(nullptr) {}
  309. };
  310. } // namespace
  311. class Benchmark {
  312. private:
  313. Cache* cache_;
  314. const FilterPolicy* filter_policy_;
  315. DB* db_;
  316. int num_;
  317. int value_size_;
  318. int entries_per_batch_;
  319. WriteOptions write_options_;
  320. int reads_;
  321. int heap_counter_;
  322. CountComparator count_comparator_;
  323. int total_thread_count_;
  324. void PrintHeader() {
  325. const int kKeySize = 16 + FLAGS_key_prefix;
  326. PrintEnvironment();
  327. std::fprintf(stdout, "Keys: %d bytes each\n", kKeySize);
  328. std::fprintf(
  329. stdout, "Values: %d bytes each (%d bytes after compression)\n",
  330. FLAGS_value_size,
  331. static_cast<int>(FLAGS_value_size * FLAGS_compression_ratio + 0.5));
  332. std::fprintf(stdout, "Entries: %d\n", num_);
  333. std::fprintf(stdout, "RawSize: %.1f MB (estimated)\n",
  334. ((static_cast<int64_t>(kKeySize + FLAGS_value_size) * num_) /
  335. 1048576.0));
  336. std::fprintf(
  337. stdout, "FileSize: %.1f MB (estimated)\n",
  338. (((kKeySize + FLAGS_value_size * FLAGS_compression_ratio) * num_) /
  339. 1048576.0));
  340. PrintWarnings();
  341. std::fprintf(stdout, "------------------------------------------------\n");
  342. }
  343. void PrintWarnings() {
  344. #if defined(__GNUC__) && !defined(__OPTIMIZE__)
  345. std::fprintf(
  346. stdout,
  347. "WARNING: Optimization is disabled: benchmarks unnecessarily slow\n");
  348. #endif
  349. #ifndef NDEBUG
  350. std::fprintf(
  351. stdout,
  352. "WARNING: Assertions are enabled; benchmarks unnecessarily slow\n");
  353. #endif
  354. // See if snappy is working by attempting to compress a compressible string
  355. const char text[] = "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy";
  356. std::string compressed;
  357. if (!port::Snappy_Compress(text, sizeof(text), &compressed)) {
  358. std::fprintf(stdout, "WARNING: Snappy compression is not enabled\n");
  359. } else if (compressed.size() >= sizeof(text)) {
  360. std::fprintf(stdout, "WARNING: Snappy compression is not effective\n");
  361. }
  362. }
  363. void PrintEnvironment() {
  364. std::fprintf(stderr, "LevelDB: version %d.%d\n", kMajorVersion,
  365. kMinorVersion);
  366. #if defined(__linux)
  367. time_t now = time(nullptr);
  368. std::fprintf(stderr, "Date: %s",
  369. ctime(&now)); // ctime() adds newline
  370. FILE* cpuinfo = std::fopen("/proc/cpuinfo", "r");
  371. if (cpuinfo != nullptr) {
  372. char line[1000];
  373. int num_cpus = 0;
  374. std::string cpu_type;
  375. std::string cache_size;
  376. while (fgets(line, sizeof(line), cpuinfo) != nullptr) {
  377. const char* sep = strchr(line, ':');
  378. if (sep == nullptr) {
  379. continue;
  380. }
  381. Slice key = TrimSpace(Slice(line, sep - 1 - line));
  382. Slice val = TrimSpace(Slice(sep + 1));
  383. if (key == "model name") {
  384. ++num_cpus;
  385. cpu_type = val.ToString();
  386. } else if (key == "cache size") {
  387. cache_size = val.ToString();
  388. }
  389. }
  390. std::fclose(cpuinfo);
  391. std::fprintf(stderr, "CPU: %d * %s\n", num_cpus, cpu_type.c_str());
  392. std::fprintf(stderr, "CPUCache: %s\n", cache_size.c_str());
  393. }
  394. #endif
  395. }
  396. public:
  397. Benchmark()
  398. : cache_(FLAGS_cache_size >= 0 ? NewLRUCache(FLAGS_cache_size) : nullptr),
  399. filter_policy_(FLAGS_bloom_bits >= 0
  400. ? NewBloomFilterPolicy(FLAGS_bloom_bits)
  401. : nullptr),
  402. db_(nullptr),
  403. num_(FLAGS_num),
  404. value_size_(FLAGS_value_size),
  405. entries_per_batch_(1),
  406. reads_(FLAGS_reads < 0 ? FLAGS_num : FLAGS_reads),
  407. heap_counter_(0),
  408. count_comparator_(BytewiseComparator()),
  409. total_thread_count_(0) {
  410. std::vector<std::string> files;
  411. g_env->GetChildren(FLAGS_db, &files);
  412. for (size_t i = 0; i < files.size(); i++) {
  413. if (Slice(files[i]).starts_with("heap-")) {
  414. g_env->RemoveFile(std::string(FLAGS_db) + "/" + files[i]);
  415. }
  416. }
  417. if (!FLAGS_use_existing_db) {
  418. DestroyDB(FLAGS_db, Options());
  419. }
  420. }
  421. ~Benchmark() {
  422. delete db_;
  423. delete cache_;
  424. delete filter_policy_;
  425. }
  426. void Run() {
  427. PrintHeader();
  428. Open();
  429. const char* benchmarks = FLAGS_benchmarks;
  430. while (benchmarks != nullptr) {
  431. const char* sep = strchr(benchmarks, ',');
  432. Slice name;
  433. if (sep == nullptr) {
  434. name = benchmarks;
  435. benchmarks = nullptr;
  436. } else {
  437. name = Slice(benchmarks, sep - benchmarks);
  438. benchmarks = sep + 1;
  439. }
  440. // Reset parameters that may be overridden below
  441. num_ = FLAGS_num;
  442. reads_ = (FLAGS_reads < 0 ? FLAGS_num : FLAGS_reads);
  443. value_size_ = FLAGS_value_size;
  444. entries_per_batch_ = 1;
  445. write_options_ = WriteOptions();
  446. void (Benchmark::*method)(ThreadState*) = nullptr;
  447. bool fresh_db = false;
  448. int num_threads = FLAGS_threads;
  449. if (name == Slice("open")) {
  450. method = &Benchmark::OpenBench;
  451. num_ /= 10000;
  452. if (num_ < 1) num_ = 1;
  453. } else if (name == Slice("fillseq")) {
  454. fresh_db = true;
  455. method = &Benchmark::WriteSeq;
  456. } else if (name == Slice("fillbatch")) {
  457. fresh_db = true;
  458. entries_per_batch_ = 1000;
  459. method = &Benchmark::WriteSeq;
  460. } else if (name == Slice("fillrandom")) {
  461. fresh_db = true;
  462. method = &Benchmark::WriteRandom;
  463. } else if (name == Slice("overwrite")) {
  464. fresh_db = false;
  465. method = &Benchmark::WriteRandom;
  466. } else if (name == Slice("fillsync")) {
  467. fresh_db = true;
  468. num_ /= 1000;
  469. write_options_.sync = true;
  470. method = &Benchmark::WriteRandom;
  471. } else if (name == Slice("fill100K")) {
  472. fresh_db = true;
  473. num_ /= 1000;
  474. value_size_ = 100 * 1000;
  475. method = &Benchmark::WriteRandom;
  476. } else if (name == Slice("readseq")) {
  477. method = &Benchmark::ReadSequential;
  478. } else if (name == Slice("readreverse")) {
  479. method = &Benchmark::ReadReverse;
  480. } else if (name == Slice("readrandom")) {
  481. method = &Benchmark::ReadRandom;
  482. } else if (name == Slice("readmissing")) {
  483. method = &Benchmark::ReadMissing;
  484. } else if (name == Slice("seekrandom")) {
  485. method = &Benchmark::SeekRandom;
  486. } else if (name == Slice("seekordered")) {
  487. method = &Benchmark::SeekOrdered;
  488. } else if (name == Slice("readhot")) {
  489. method = &Benchmark::ReadHot;
  490. } else if (name == Slice("readrandomsmall")) {
  491. reads_ /= 1000;
  492. method = &Benchmark::ReadRandom;
  493. } else if (name == Slice("deleteseq")) {
  494. method = &Benchmark::DeleteSeq;
  495. } else if (name == Slice("deleterandom")) {
  496. method = &Benchmark::DeleteRandom;
  497. } else if (name == Slice("readwhilewriting")) {
  498. num_threads++; // Add extra thread for writing
  499. method = &Benchmark::ReadWhileWriting;
  500. } else if (name == Slice("compact")) {
  501. method = &Benchmark::Compact;
  502. } else if (name == Slice("crc32c")) {
  503. method = &Benchmark::Crc32c;
  504. } else if (name == Slice("snappycomp")) {
  505. method = &Benchmark::SnappyCompress;
  506. } else if (name == Slice("snappyuncomp")) {
  507. method = &Benchmark::SnappyUncompress;
  508. } else if (name == Slice("heapprofile")) {
  509. HeapProfile();
  510. } else if (name == Slice("stats")) {
  511. PrintStats("leveldb.stats");
  512. } else if (name == Slice("sstables")) {
  513. PrintStats("leveldb.sstables");
  514. } else {
  515. if (!name.empty()) { // No error message for empty name
  516. std::fprintf(stderr, "unknown benchmark '%s'\n",
  517. name.ToString().c_str());
  518. }
  519. }
  520. if (fresh_db) {
  521. if (FLAGS_use_existing_db) {
  522. std::fprintf(stdout, "%-12s : skipped (--use_existing_db is true)\n",
  523. name.ToString().c_str());
  524. method = nullptr;
  525. } else {
  526. delete db_;
  527. db_ = nullptr;
  528. DestroyDB(FLAGS_db, Options());
  529. Open();
  530. }
  531. }
  532. if (method != nullptr) {
  533. RunBenchmark(num_threads, name, method);
  534. }
  535. }
  536. }
  537. private:
  538. struct ThreadArg {
  539. Benchmark* bm;
  540. SharedState* shared;
  541. ThreadState* thread;
  542. void (Benchmark::*method)(ThreadState*);
  543. };
  544. static void ThreadBody(void* v) {
  545. ThreadArg* arg = reinterpret_cast<ThreadArg*>(v);
  546. SharedState* shared = arg->shared;
  547. ThreadState* thread = arg->thread;
  548. {
  549. MutexLock l(&shared->mu);
  550. shared->num_initialized++;
  551. if (shared->num_initialized >= shared->total) {
  552. shared->cv.SignalAll();
  553. }
  554. while (!shared->start) {
  555. shared->cv.Wait();
  556. }
  557. }
  558. thread->stats.Start();
  559. (arg->bm->*(arg->method))(thread);
  560. thread->stats.Stop();
  561. {
  562. MutexLock l(&shared->mu);
  563. shared->num_done++;
  564. if (shared->num_done >= shared->total) {
  565. shared->cv.SignalAll();
  566. }
  567. }
  568. }
  569. void RunBenchmark(int n, Slice name,
  570. void (Benchmark::*method)(ThreadState*)) {
  571. SharedState shared(n);
  572. ThreadArg* arg = new ThreadArg[n];
  573. for (int i = 0; i < n; i++) {
  574. arg[i].bm = this;
  575. arg[i].method = method;
  576. arg[i].shared = &shared;
  577. ++total_thread_count_;
  578. // Seed the thread's random state deterministically based upon thread
  579. // creation across all benchmarks. This ensures that the seeds are unique
  580. // but reproducible when rerunning the same set of benchmarks.
  581. arg[i].thread = new ThreadState(i, /*seed=*/1000 + total_thread_count_);
  582. arg[i].thread->shared = &shared;
  583. g_env->StartThread(ThreadBody, &arg[i]);
  584. }
  585. shared.mu.Lock();
  586. while (shared.num_initialized < n) {
  587. shared.cv.Wait();
  588. }
  589. shared.start = true;
  590. shared.cv.SignalAll();
  591. while (shared.num_done < n) {
  592. shared.cv.Wait();
  593. }
  594. shared.mu.Unlock();
  595. for (int i = 1; i < n; i++) {
  596. arg[0].thread->stats.Merge(arg[i].thread->stats);
  597. }
  598. arg[0].thread->stats.Report(name);
  599. if (FLAGS_comparisons) {
  600. fprintf(stdout, "Comparisons: %zu\n", count_comparator_.comparisons());
  601. count_comparator_.reset();
  602. fflush(stdout);
  603. }
  604. for (int i = 0; i < n; i++) {
  605. delete arg[i].thread;
  606. }
  607. delete[] arg;
  608. }
  609. void Crc32c(ThreadState* thread) {
  610. // Checksum about 500MB of data total
  611. const int size = 4096;
  612. const char* label = "(4K per op)";
  613. std::string data(size, 'x');
  614. int64_t bytes = 0;
  615. uint32_t crc = 0;
  616. while (bytes < 500 * 1048576) {
  617. crc = crc32c::Value(data.data(), size);
  618. thread->stats.FinishedSingleOp();
  619. bytes += size;
  620. }
  621. // Print so result is not dead
  622. std::fprintf(stderr, "... crc=0x%x\r", static_cast<unsigned int>(crc));
  623. thread->stats.AddBytes(bytes);
  624. thread->stats.AddMessage(label);
  625. }
  626. void SnappyCompress(ThreadState* thread) {
  627. RandomGenerator gen;
  628. Slice input = gen.Generate(Options().block_size);
  629. int64_t bytes = 0;
  630. int64_t produced = 0;
  631. bool ok = true;
  632. std::string compressed;
  633. while (ok && bytes < 1024 * 1048576) { // Compress 1G
  634. ok = port::Snappy_Compress(input.data(), input.size(), &compressed);
  635. produced += compressed.size();
  636. bytes += input.size();
  637. thread->stats.FinishedSingleOp();
  638. }
  639. if (!ok) {
  640. thread->stats.AddMessage("(snappy failure)");
  641. } else {
  642. char buf[100];
  643. std::snprintf(buf, sizeof(buf), "(output: %.1f%%)",
  644. (produced * 100.0) / bytes);
  645. thread->stats.AddMessage(buf);
  646. thread->stats.AddBytes(bytes);
  647. }
  648. }
  649. void SnappyUncompress(ThreadState* thread) {
  650. RandomGenerator gen;
  651. Slice input = gen.Generate(Options().block_size);
  652. std::string compressed;
  653. bool ok = port::Snappy_Compress(input.data(), input.size(), &compressed);
  654. int64_t bytes = 0;
  655. char* uncompressed = new char[input.size()];
  656. while (ok && bytes < 1024 * 1048576) { // Compress 1G
  657. ok = port::Snappy_Uncompress(compressed.data(), compressed.size(),
  658. uncompressed);
  659. bytes += input.size();
  660. thread->stats.FinishedSingleOp();
  661. }
  662. delete[] uncompressed;
  663. if (!ok) {
  664. thread->stats.AddMessage("(snappy failure)");
  665. } else {
  666. thread->stats.AddBytes(bytes);
  667. }
  668. }
  669. void Open() {
  670. assert(db_ == nullptr);
  671. Options options;
  672. options.env = g_env;
  673. options.create_if_missing = !FLAGS_use_existing_db;
  674. options.block_cache = cache_;
  675. options.write_buffer_size = FLAGS_write_buffer_size;
  676. options.max_file_size = FLAGS_max_file_size;
  677. options.block_size = FLAGS_block_size;
  678. if (FLAGS_comparisons) {
  679. options.comparator = &count_comparator_;
  680. }
  681. options.max_open_files = FLAGS_open_files;
  682. options.filter_policy = filter_policy_;
  683. options.reuse_logs = FLAGS_reuse_logs;
  684. Status s = DB::Open(options, FLAGS_db, &db_);
  685. if (!s.ok()) {
  686. std::fprintf(stderr, "open error: %s\n", s.ToString().c_str());
  687. std::exit(1);
  688. }
  689. }
  690. void OpenBench(ThreadState* thread) {
  691. for (int i = 0; i < num_; i++) {
  692. delete db_;
  693. Open();
  694. thread->stats.FinishedSingleOp();
  695. }
  696. }
  697. void WriteSeq(ThreadState* thread) { DoWrite(thread, true); }
  698. void WriteRandom(ThreadState* thread) { DoWrite(thread, false); }
  699. void DoWrite(ThreadState* thread, bool seq) {
  700. if (num_ != FLAGS_num) {
  701. char msg[100];
  702. std::snprintf(msg, sizeof(msg), "(%d ops)", num_);
  703. thread->stats.AddMessage(msg);
  704. }
  705. RandomGenerator gen;
  706. WriteBatch batch;
  707. Status s;
  708. int64_t bytes = 0;
  709. KeyBuffer key;
  710. for (int i = 0; i < num_; i += entries_per_batch_) {
  711. batch.Clear();
  712. for (int j = 0; j < entries_per_batch_; j++) {
  713. const int k = seq ? i + j : thread->rand.Uniform(FLAGS_num);
  714. key.Set(k);
  715. batch.Put(key.slice(), gen.Generate(value_size_));
  716. bytes += value_size_ + key.slice().size();
  717. thread->stats.FinishedSingleOp();
  718. }
  719. s = db_->Write(write_options_, &batch);
  720. if (!s.ok()) {
  721. std::fprintf(stderr, "put error: %s\n", s.ToString().c_str());
  722. std::exit(1);
  723. }
  724. }
  725. thread->stats.AddBytes(bytes);
  726. }
  727. void ReadSequential(ThreadState* thread) {
  728. Iterator* iter = db_->NewIterator(ReadOptions());
  729. int i = 0;
  730. int64_t bytes = 0;
  731. for (iter->SeekToFirst(); i < reads_ && iter->Valid(); iter->Next()) {
  732. bytes += iter->key().size() + iter->value().size();
  733. thread->stats.FinishedSingleOp();
  734. ++i;
  735. }
  736. delete iter;
  737. thread->stats.AddBytes(bytes);
  738. }
  739. void ReadReverse(ThreadState* thread) {
  740. Iterator* iter = db_->NewIterator(ReadOptions());
  741. int i = 0;
  742. int64_t bytes = 0;
  743. for (iter->SeekToLast(); i < reads_ && iter->Valid(); iter->Prev()) {
  744. bytes += iter->key().size() + iter->value().size();
  745. thread->stats.FinishedSingleOp();
  746. ++i;
  747. }
  748. delete iter;
  749. thread->stats.AddBytes(bytes);
  750. }
  751. void ReadRandom(ThreadState* thread) {
  752. ReadOptions options;
  753. std::string value;
  754. int found = 0;
  755. KeyBuffer key;
  756. for (int i = 0; i < reads_; i++) {
  757. const int k = thread->rand.Uniform(FLAGS_num);
  758. key.Set(k);
  759. if (db_->Get(options, key.slice(), &value).ok()) {
  760. found++;
  761. }
  762. thread->stats.FinishedSingleOp();
  763. }
  764. char msg[100];
  765. std::snprintf(msg, sizeof(msg), "(%d of %d found)", found, num_);
  766. thread->stats.AddMessage(msg);
  767. }
  768. void ReadMissing(ThreadState* thread) {
  769. ReadOptions options;
  770. std::string value;
  771. KeyBuffer key;
  772. for (int i = 0; i < reads_; i++) {
  773. const int k = thread->rand.Uniform(FLAGS_num);
  774. key.Set(k);
  775. Slice s = Slice(key.slice().data(), key.slice().size() - 1);
  776. db_->Get(options, s, &value);
  777. thread->stats.FinishedSingleOp();
  778. }
  779. }
  780. void ReadHot(ThreadState* thread) {
  781. ReadOptions options;
  782. std::string value;
  783. const int range = (FLAGS_num + 99) / 100;
  784. KeyBuffer key;
  785. for (int i = 0; i < reads_; i++) {
  786. const int k = thread->rand.Uniform(range);
  787. key.Set(k);
  788. db_->Get(options, key.slice(), &value);
  789. thread->stats.FinishedSingleOp();
  790. }
  791. }
  792. void SeekRandom(ThreadState* thread) {
  793. ReadOptions options;
  794. int found = 0;
  795. KeyBuffer key;
  796. for (int i = 0; i < reads_; i++) {
  797. Iterator* iter = db_->NewIterator(options);
  798. const int k = thread->rand.Uniform(FLAGS_num);
  799. key.Set(k);
  800. iter->Seek(key.slice());
  801. if (iter->Valid() && iter->key() == key.slice()) found++;
  802. delete iter;
  803. thread->stats.FinishedSingleOp();
  804. }
  805. char msg[100];
  806. snprintf(msg, sizeof(msg), "(%d of %d found)", found, num_);
  807. thread->stats.AddMessage(msg);
  808. }
  809. void SeekOrdered(ThreadState* thread) {
  810. ReadOptions options;
  811. Iterator* iter = db_->NewIterator(options);
  812. int found = 0;
  813. int k = 0;
  814. KeyBuffer key;
  815. for (int i = 0; i < reads_; i++) {
  816. k = (k + (thread->rand.Uniform(100))) % FLAGS_num;
  817. key.Set(k);
  818. iter->Seek(key.slice());
  819. if (iter->Valid() && iter->key() == key.slice()) found++;
  820. thread->stats.FinishedSingleOp();
  821. }
  822. delete iter;
  823. char msg[100];
  824. std::snprintf(msg, sizeof(msg), "(%d of %d found)", found, num_);
  825. thread->stats.AddMessage(msg);
  826. }
  827. void DoDelete(ThreadState* thread, bool seq) {
  828. RandomGenerator gen;
  829. WriteBatch batch;
  830. Status s;
  831. KeyBuffer key;
  832. for (int i = 0; i < num_; i += entries_per_batch_) {
  833. batch.Clear();
  834. for (int j = 0; j < entries_per_batch_; j++) {
  835. const int k = seq ? i + j : (thread->rand.Uniform(FLAGS_num));
  836. key.Set(k);
  837. batch.Delete(key.slice());
  838. thread->stats.FinishedSingleOp();
  839. }
  840. s = db_->Write(write_options_, &batch);
  841. if (!s.ok()) {
  842. std::fprintf(stderr, "del error: %s\n", s.ToString().c_str());
  843. std::exit(1);
  844. }
  845. }
  846. }
  847. void DeleteSeq(ThreadState* thread) { DoDelete(thread, true); }
  848. void DeleteRandom(ThreadState* thread) { DoDelete(thread, false); }
  849. void ReadWhileWriting(ThreadState* thread) {
  850. if (thread->tid > 0) {
  851. ReadRandom(thread);
  852. } else {
  853. // Special thread that keeps writing until other threads are done.
  854. RandomGenerator gen;
  855. KeyBuffer key;
  856. while (true) {
  857. {
  858. MutexLock l(&thread->shared->mu);
  859. if (thread->shared->num_done + 1 >= thread->shared->num_initialized) {
  860. // Other threads have finished
  861. break;
  862. }
  863. }
  864. const int k = thread->rand.Uniform(FLAGS_num);
  865. key.Set(k);
  866. Status s =
  867. db_->Put(write_options_, key.slice(), gen.Generate(value_size_));
  868. if (!s.ok()) {
  869. std::fprintf(stderr, "put error: %s\n", s.ToString().c_str());
  870. std::exit(1);
  871. }
  872. }
  873. // Do not count any of the preceding work/delay in stats.
  874. thread->stats.Start();
  875. }
  876. }
  877. void Compact(ThreadState* thread) { db_->CompactRange(nullptr, nullptr); }
  878. void PrintStats(const char* key) {
  879. std::string stats;
  880. if (!db_->GetProperty(key, &stats)) {
  881. stats = "(failed)";
  882. }
  883. std::fprintf(stdout, "\n%s\n", stats.c_str());
  884. }
  885. static void WriteToFile(void* arg, const char* buf, int n) {
  886. reinterpret_cast<WritableFile*>(arg)->Append(Slice(buf, n));
  887. }
  888. void HeapProfile() {
  889. char fname[100];
  890. std::snprintf(fname, sizeof(fname), "%s/heap-%04d", FLAGS_db,
  891. ++heap_counter_);
  892. WritableFile* file;
  893. Status s = g_env->NewWritableFile(fname, &file);
  894. if (!s.ok()) {
  895. std::fprintf(stderr, "%s\n", s.ToString().c_str());
  896. return;
  897. }
  898. bool ok = port::GetHeapProfile(WriteToFile, file);
  899. delete file;
  900. if (!ok) {
  901. std::fprintf(stderr, "heap profiling not supported\n");
  902. g_env->RemoveFile(fname);
  903. }
  904. }
  905. };
  906. } // namespace leveldb
  907. int main(int argc, char** argv) {
  908. FLAGS_write_buffer_size = leveldb::Options().write_buffer_size;
  909. FLAGS_max_file_size = leveldb::Options().max_file_size;
  910. FLAGS_block_size = leveldb::Options().block_size;
  911. FLAGS_open_files = leveldb::Options().max_open_files;
  912. std::string default_db_path;
  913. for (int i = 1; i < argc; i++) {
  914. double d;
  915. int n;
  916. char junk;
  917. if (leveldb::Slice(argv[i]).starts_with("--benchmarks=")) {
  918. FLAGS_benchmarks = argv[i] + strlen("--benchmarks=");
  919. } else if (sscanf(argv[i], "--compression_ratio=%lf%c", &d, &junk) == 1) {
  920. FLAGS_compression_ratio = d;
  921. } else if (sscanf(argv[i], "--histogram=%d%c", &n, &junk) == 1 &&
  922. (n == 0 || n == 1)) {
  923. FLAGS_histogram = n;
  924. } else if (sscanf(argv[i], "--comparisons=%d%c", &n, &junk) == 1 &&
  925. (n == 0 || n == 1)) {
  926. FLAGS_comparisons = n;
  927. } else if (sscanf(argv[i], "--use_existing_db=%d%c", &n, &junk) == 1 &&
  928. (n == 0 || n == 1)) {
  929. FLAGS_use_existing_db = n;
  930. } else if (sscanf(argv[i], "--reuse_logs=%d%c", &n, &junk) == 1 &&
  931. (n == 0 || n == 1)) {
  932. FLAGS_reuse_logs = n;
  933. } else if (sscanf(argv[i], "--num=%d%c", &n, &junk) == 1) {
  934. FLAGS_num = n;
  935. } else if (sscanf(argv[i], "--reads=%d%c", &n, &junk) == 1) {
  936. FLAGS_reads = n;
  937. } else if (sscanf(argv[i], "--threads=%d%c", &n, &junk) == 1) {
  938. FLAGS_threads = n;
  939. } else if (sscanf(argv[i], "--value_size=%d%c", &n, &junk) == 1) {
  940. FLAGS_value_size = n;
  941. } else if (sscanf(argv[i], "--write_buffer_size=%d%c", &n, &junk) == 1) {
  942. FLAGS_write_buffer_size = n;
  943. } else if (sscanf(argv[i], "--max_file_size=%d%c", &n, &junk) == 1) {
  944. FLAGS_max_file_size = n;
  945. } else if (sscanf(argv[i], "--block_size=%d%c", &n, &junk) == 1) {
  946. FLAGS_block_size = n;
  947. } else if (sscanf(argv[i], "--key_prefix=%d%c", &n, &junk) == 1) {
  948. FLAGS_key_prefix = n;
  949. } else if (sscanf(argv[i], "--cache_size=%d%c", &n, &junk) == 1) {
  950. FLAGS_cache_size = n;
  951. } else if (sscanf(argv[i], "--bloom_bits=%d%c", &n, &junk) == 1) {
  952. FLAGS_bloom_bits = n;
  953. } else if (sscanf(argv[i], "--open_files=%d%c", &n, &junk) == 1) {
  954. FLAGS_open_files = n;
  955. } else if (strncmp(argv[i], "--db=", 5) == 0) {
  956. FLAGS_db = argv[i] + 5;
  957. } else {
  958. std::fprintf(stderr, "Invalid flag '%s'\n", argv[i]);
  959. std::exit(1);
  960. }
  961. }
  962. leveldb::g_env = leveldb::Env::Default();
  963. // Choose a location for the test database if none given with --db=<path>
  964. if (FLAGS_db == nullptr) {
  965. leveldb::g_env->GetTestDirectory(&default_db_path);
  966. default_db_path += "/dbbench";
  967. FLAGS_db = default_db_path.c_str();
  968. }
  969. leveldb::Benchmark benchmark;
  970. benchmark.Run();
  971. return 0;
  972. }