作者: 韩晨旭 10225101440 李畅 10225102463

1016 lines
30 KiB

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