10225501448 李度 10225101546 陈胤遒 10215501422 高宇菲
Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

1020 linhas
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)
há 10 anos
  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 "db/db_impl.h"
  8. #include "db/version_set.h"
  9. #include "leveldb/cache.h"
  10. #include "leveldb/db.h"
  11. #include "leveldb/env.h"
  12. #include "leveldb/write_batch.h"
  13. #include "port/port.h"
  14. #include "util/crc32c.h"
  15. #include "util/histogram.h"
  16. #include "util/mutexlock.h"
  17. #include "util/random.h"
  18. #include "util/testutil.h"
  19. // Comma-separated list of operations to run in the specified order
  20. // Actual benchmarks:
  21. // fillseq -- write N values in sequential key order in async mode
  22. // fillrandom -- write N values in random key order in async mode
  23. // overwrite -- overwrite N values in random key order in async mode
  24. // fillsync -- write N/100 values in random key order in sync mode
  25. // fill100K -- write N/1000 100K values in random order in async mode
  26. // deleteseq -- delete N keys in sequential order
  27. // deleterandom -- delete N keys in random order
  28. // readseq -- read N times sequentially
  29. // readreverse -- read N times in reverse order
  30. // readrandom -- read N times in random order
  31. // readmissing -- read N missing keys in random order
  32. // readhot -- read N times in random order from 1% section of DB
  33. // seekrandom -- N random seeks
  34. // open -- cost of opening a DB
  35. // crc32c -- repeated crc32c of 4K of data
  36. // acquireload -- load N*1000 times
  37. // Meta operations:
  38. // compact -- Compact the entire DB
  39. // stats -- Print DB stats
  40. // sstables -- Print sstable info
  41. // heapprofile -- Dump a heap profile (if supported by this port)
  42. static const char* FLAGS_benchmarks =
  43. "fillseq,"
  44. "fillsync,"
  45. "fillrandom,"
  46. "overwrite,"
  47. "readrandom,"
  48. "readrandom," // Extra run to allow previous compactions to quiesce
  49. "readseq,"
  50. "readreverse,"
  51. "compact,"
  52. "readrandom,"
  53. "readseq,"
  54. "readreverse,"
  55. "fill100K,"
  56. "crc32c,"
  57. "snappycomp,"
  58. "snappyuncomp,"
  59. "acquireload,"
  60. ;
  61. // Number of key/values to place in database
  62. static int FLAGS_num = 1000000;
  63. // Number of read operations to do. If negative, do FLAGS_num reads.
  64. static int FLAGS_reads = -1;
  65. // Number of concurrent threads to run.
  66. static int FLAGS_threads = 1;
  67. // Size of each value
  68. static int FLAGS_value_size = 100;
  69. // Arrange to generate values that shrink to this fraction of
  70. // their original size after compression
  71. static double FLAGS_compression_ratio = 0.5;
  72. // Print histogram of operation timings
  73. static bool FLAGS_histogram = false;
  74. // Number of bytes to buffer in memtable before compacting
  75. // (initialized to default value by "main")
  76. static int FLAGS_write_buffer_size = 0;
  77. // Number of bytes written to each file.
  78. // (initialized to default value by "main")
  79. static int FLAGS_max_file_size = 0;
  80. // Approximate size of user data packed per block (before compression.
  81. // (initialized to default value by "main")
  82. static int FLAGS_block_size = 0;
  83. // Number of bytes to use as a cache of uncompressed data.
  84. // Negative means use default settings.
  85. static int FLAGS_cache_size = -1;
  86. // Maximum number of files to keep open at the same time (use default if == 0)
  87. static int FLAGS_open_files = 0;
  88. // Bloom filter bits per key.
  89. // Negative means use default settings.
  90. static int FLAGS_bloom_bits = -1;
  91. // If true, do not destroy the existing database. If you set this
  92. // flag and also specify a benchmark that wants a fresh database, that
  93. // benchmark will fail.
  94. static bool FLAGS_use_existing_db = false;
  95. // If true, reuse existing log/MANIFEST files when re-opening a database.
  96. static bool FLAGS_reuse_logs = false;
  97. // Use the db with the following name.
  98. static const char* FLAGS_db = NULL;
  99. namespace leveldb {
  100. namespace {
  101. leveldb::Env* g_env = NULL;
  102. // Helper for quickly generating random data.
  103. class RandomGenerator {
  104. private:
  105. std::string data_;
  106. int pos_;
  107. public:
  108. RandomGenerator() {
  109. // We use a limited amount of data over and over again and ensure
  110. // that it is larger than the compression window (32KB), and also
  111. // large enough to serve all typical value sizes we want to write.
  112. Random rnd(301);
  113. std::string piece;
  114. while (data_.size() < 1048576) {
  115. // Add a short fragment that is as compressible as specified
  116. // by FLAGS_compression_ratio.
  117. test::CompressibleString(&rnd, FLAGS_compression_ratio, 100, &piece);
  118. data_.append(piece);
  119. }
  120. pos_ = 0;
  121. }
  122. Slice Generate(size_t len) {
  123. if (pos_ + len > data_.size()) {
  124. pos_ = 0;
  125. assert(len < data_.size());
  126. }
  127. pos_ += len;
  128. return Slice(data_.data() + pos_ - len, len);
  129. }
  130. };
  131. #if defined(__linux)
  132. static Slice TrimSpace(Slice s) {
  133. size_t start = 0;
  134. while (start < s.size() && isspace(s[start])) {
  135. start++;
  136. }
  137. size_t limit = s.size();
  138. while (limit > start && isspace(s[limit-1])) {
  139. limit--;
  140. }
  141. return Slice(s.data() + start, limit - start);
  142. }
  143. #endif
  144. static void AppendWithSpace(std::string* str, Slice msg) {
  145. if (msg.empty()) return;
  146. if (!str->empty()) {
  147. str->push_back(' ');
  148. }
  149. str->append(msg.data(), msg.size());
  150. }
  151. class Stats {
  152. private:
  153. double start_;
  154. double finish_;
  155. double seconds_;
  156. int done_;
  157. int next_report_;
  158. int64_t bytes_;
  159. double last_op_finish_;
  160. Histogram hist_;
  161. std::string message_;
  162. public:
  163. Stats() { Start(); }
  164. void Start() {
  165. next_report_ = 100;
  166. last_op_finish_ = start_;
  167. hist_.Clear();
  168. done_ = 0;
  169. bytes_ = 0;
  170. seconds_ = 0;
  171. start_ = g_env->NowMicros();
  172. finish_ = start_;
  173. message_.clear();
  174. }
  175. void Merge(const Stats& other) {
  176. hist_.Merge(other.hist_);
  177. done_ += other.done_;
  178. bytes_ += other.bytes_;
  179. seconds_ += other.seconds_;
  180. if (other.start_ < start_) start_ = other.start_;
  181. if (other.finish_ > finish_) finish_ = other.finish_;
  182. // Just keep the messages from one thread
  183. if (message_.empty()) message_ = other.message_;
  184. }
  185. void Stop() {
  186. finish_ = g_env->NowMicros();
  187. seconds_ = (finish_ - start_) * 1e-6;
  188. }
  189. void AddMessage(Slice msg) {
  190. AppendWithSpace(&message_, msg);
  191. }
  192. void FinishedSingleOp() {
  193. if (FLAGS_histogram) {
  194. double now = g_env->NowMicros();
  195. double micros = now - last_op_finish_;
  196. hist_.Add(micros);
  197. if (micros > 20000) {
  198. fprintf(stderr, "long op: %.1f micros%30s\r", micros, "");
  199. fflush(stderr);
  200. }
  201. last_op_finish_ = now;
  202. }
  203. done_++;
  204. if (done_ >= next_report_) {
  205. if (next_report_ < 1000) next_report_ += 100;
  206. else if (next_report_ < 5000) next_report_ += 500;
  207. else if (next_report_ < 10000) next_report_ += 1000;
  208. else if (next_report_ < 50000) next_report_ += 5000;
  209. else if (next_report_ < 100000) next_report_ += 10000;
  210. else if (next_report_ < 500000) next_report_ += 50000;
  211. else next_report_ += 100000;
  212. fprintf(stderr, "... finished %d ops%30s\r", done_, "");
  213. fflush(stderr);
  214. }
  215. }
  216. void AddBytes(int64_t n) {
  217. bytes_ += n;
  218. }
  219. void Report(const Slice& name) {
  220. // Pretend at least one op was done in case we are running a benchmark
  221. // that does not call FinishedSingleOp().
  222. if (done_ < 1) done_ = 1;
  223. std::string extra;
  224. if (bytes_ > 0) {
  225. // Rate is computed on actual elapsed time, not the sum of per-thread
  226. // elapsed times.
  227. double elapsed = (finish_ - start_) * 1e-6;
  228. char rate[100];
  229. snprintf(rate, sizeof(rate), "%6.1f MB/s",
  230. (bytes_ / 1048576.0) / elapsed);
  231. extra = rate;
  232. }
  233. AppendWithSpace(&extra, message_);
  234. fprintf(stdout, "%-12s : %11.3f micros/op;%s%s\n",
  235. name.ToString().c_str(),
  236. seconds_ * 1e6 / done_,
  237. (extra.empty() ? "" : " "),
  238. extra.c_str());
  239. if (FLAGS_histogram) {
  240. fprintf(stdout, "Microseconds per op:\n%s\n", hist_.ToString().c_str());
  241. }
  242. fflush(stdout);
  243. }
  244. };
  245. // State shared by all concurrent executions of the same benchmark.
  246. struct SharedState {
  247. port::Mutex mu;
  248. port::CondVar cv;
  249. int total;
  250. // Each thread goes through the following states:
  251. // (1) initializing
  252. // (2) waiting for others to be initialized
  253. // (3) running
  254. // (4) done
  255. int num_initialized;
  256. int num_done;
  257. bool start;
  258. SharedState() : cv(&mu) { }
  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(NULL);
  324. fprintf(stderr, "Date: %s", ctime(&now)); // ctime() adds newline
  325. FILE* cpuinfo = fopen("/proc/cpuinfo", "r");
  326. if (cpuinfo != NULL) {
  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) != NULL) {
  332. const char* sep = strchr(line, ':');
  333. if (sep == NULL) {
  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) : NULL),
  354. filter_policy_(FLAGS_bloom_bits >= 0
  355. ? NewBloomFilterPolicy(FLAGS_bloom_bits)
  356. : NULL),
  357. db_(NULL),
  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 != NULL) {
  384. const char* sep = strchr(benchmarks, ',');
  385. Slice name;
  386. if (sep == NULL) {
  387. name = benchmarks;
  388. benchmarks = NULL;
  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*) = NULL;
  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 = NULL;
  477. } else {
  478. delete db_;
  479. db_ = NULL;
  480. DestroyDB(FLAGS_db, Options());
  481. Open();
  482. }
  483. }
  484. if (method != NULL) {
  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;
  524. shared.total = n;
  525. shared.num_initialized = 0;
  526. shared.num_done = 0;
  527. shared.start = false;
  528. ThreadArg* arg = new ThreadArg[n];
  529. for (int i = 0; i < n; i++) {
  530. arg[i].bm = this;
  531. arg[i].method = method;
  532. arg[i].shared = &shared;
  533. arg[i].thread = new ThreadState(i);
  534. arg[i].thread->shared = &shared;
  535. g_env->StartThread(ThreadBody, &arg[i]);
  536. }
  537. shared.mu.Lock();
  538. while (shared.num_initialized < n) {
  539. shared.cv.Wait();
  540. }
  541. shared.start = true;
  542. shared.cv.SignalAll();
  543. while (shared.num_done < n) {
  544. shared.cv.Wait();
  545. }
  546. shared.mu.Unlock();
  547. for (int i = 1; i < n; i++) {
  548. arg[0].thread->stats.Merge(arg[i].thread->stats);
  549. }
  550. arg[0].thread->stats.Report(name);
  551. for (int i = 0; i < n; i++) {
  552. delete arg[i].thread;
  553. }
  554. delete[] arg;
  555. }
  556. void Crc32c(ThreadState* thread) {
  557. // Checksum about 500MB of data total
  558. const int size = 4096;
  559. const char* label = "(4K per op)";
  560. std::string data(size, 'x');
  561. int64_t bytes = 0;
  562. uint32_t crc = 0;
  563. while (bytes < 500 * 1048576) {
  564. crc = crc32c::Value(data.data(), size);
  565. thread->stats.FinishedSingleOp();
  566. bytes += size;
  567. }
  568. // Print so result is not dead
  569. fprintf(stderr, "... crc=0x%x\r", static_cast<unsigned int>(crc));
  570. thread->stats.AddBytes(bytes);
  571. thread->stats.AddMessage(label);
  572. }
  573. void AcquireLoad(ThreadState* thread) {
  574. int dummy;
  575. port::AtomicPointer ap(&dummy);
  576. int count = 0;
  577. void *ptr = NULL;
  578. thread->stats.AddMessage("(each op is 1000 loads)");
  579. while (count < 100000) {
  580. for (int i = 0; i < 1000; i++) {
  581. ptr = ap.Acquire_Load();
  582. }
  583. count++;
  584. thread->stats.FinishedSingleOp();
  585. }
  586. if (ptr == NULL) exit(1); // Disable unused variable warning.
  587. }
  588. void SnappyCompress(ThreadState* thread) {
  589. RandomGenerator gen;
  590. Slice input = gen.Generate(Options().block_size);
  591. int64_t bytes = 0;
  592. int64_t produced = 0;
  593. bool ok = true;
  594. std::string compressed;
  595. while (ok && bytes < 1024 * 1048576) { // Compress 1G
  596. ok = port::Snappy_Compress(input.data(), input.size(), &compressed);
  597. produced += compressed.size();
  598. bytes += input.size();
  599. thread->stats.FinishedSingleOp();
  600. }
  601. if (!ok) {
  602. thread->stats.AddMessage("(snappy failure)");
  603. } else {
  604. char buf[100];
  605. snprintf(buf, sizeof(buf), "(output: %.1f%%)",
  606. (produced * 100.0) / bytes);
  607. thread->stats.AddMessage(buf);
  608. thread->stats.AddBytes(bytes);
  609. }
  610. }
  611. void SnappyUncompress(ThreadState* thread) {
  612. RandomGenerator gen;
  613. Slice input = gen.Generate(Options().block_size);
  614. std::string compressed;
  615. bool ok = port::Snappy_Compress(input.data(), input.size(), &compressed);
  616. int64_t bytes = 0;
  617. char* uncompressed = new char[input.size()];
  618. while (ok && bytes < 1024 * 1048576) { // Compress 1G
  619. ok = port::Snappy_Uncompress(compressed.data(), compressed.size(),
  620. uncompressed);
  621. bytes += input.size();
  622. thread->stats.FinishedSingleOp();
  623. }
  624. delete[] uncompressed;
  625. if (!ok) {
  626. thread->stats.AddMessage("(snappy failure)");
  627. } else {
  628. thread->stats.AddBytes(bytes);
  629. }
  630. }
  631. void Open() {
  632. assert(db_ == NULL);
  633. Options options;
  634. options.env = g_env;
  635. options.create_if_missing = !FLAGS_use_existing_db;
  636. options.block_cache = cache_;
  637. options.write_buffer_size = FLAGS_write_buffer_size;
  638. options.max_file_size = FLAGS_max_file_size;
  639. options.block_size = FLAGS_block_size;
  640. options.max_open_files = FLAGS_open_files;
  641. options.filter_policy = filter_policy_;
  642. options.reuse_logs = FLAGS_reuse_logs;
  643. Status s = DB::Open(options, FLAGS_db, &db_);
  644. if (!s.ok()) {
  645. fprintf(stderr, "open error: %s\n", s.ToString().c_str());
  646. exit(1);
  647. }
  648. }
  649. void OpenBench(ThreadState* thread) {
  650. for (int i = 0; i < num_; i++) {
  651. delete db_;
  652. Open();
  653. thread->stats.FinishedSingleOp();
  654. }
  655. }
  656. void WriteSeq(ThreadState* thread) {
  657. DoWrite(thread, true);
  658. }
  659. void WriteRandom(ThreadState* thread) {
  660. DoWrite(thread, false);
  661. }
  662. void DoWrite(ThreadState* thread, bool seq) {
  663. if (num_ != FLAGS_num) {
  664. char msg[100];
  665. snprintf(msg, sizeof(msg), "(%d ops)", num_);
  666. thread->stats.AddMessage(msg);
  667. }
  668. RandomGenerator gen;
  669. WriteBatch batch;
  670. Status s;
  671. int64_t bytes = 0;
  672. for (int i = 0; i < num_; i += entries_per_batch_) {
  673. batch.Clear();
  674. for (int j = 0; j < entries_per_batch_; j++) {
  675. const int k = seq ? i+j : (thread->rand.Next() % FLAGS_num);
  676. char key[100];
  677. snprintf(key, sizeof(key), "%016d", k);
  678. batch.Put(key, gen.Generate(value_size_));
  679. bytes += value_size_ + strlen(key);
  680. thread->stats.FinishedSingleOp();
  681. }
  682. s = db_->Write(write_options_, &batch);
  683. if (!s.ok()) {
  684. fprintf(stderr, "put error: %s\n", s.ToString().c_str());
  685. exit(1);
  686. }
  687. }
  688. thread->stats.AddBytes(bytes);
  689. }
  690. void ReadSequential(ThreadState* thread) {
  691. Iterator* iter = db_->NewIterator(ReadOptions());
  692. int i = 0;
  693. int64_t bytes = 0;
  694. for (iter->SeekToFirst(); i < reads_ && iter->Valid(); iter->Next()) {
  695. bytes += iter->key().size() + iter->value().size();
  696. thread->stats.FinishedSingleOp();
  697. ++i;
  698. }
  699. delete iter;
  700. thread->stats.AddBytes(bytes);
  701. }
  702. void ReadReverse(ThreadState* thread) {
  703. Iterator* iter = db_->NewIterator(ReadOptions());
  704. int i = 0;
  705. int64_t bytes = 0;
  706. for (iter->SeekToLast(); i < reads_ && iter->Valid(); iter->Prev()) {
  707. bytes += iter->key().size() + iter->value().size();
  708. thread->stats.FinishedSingleOp();
  709. ++i;
  710. }
  711. delete iter;
  712. thread->stats.AddBytes(bytes);
  713. }
  714. void ReadRandom(ThreadState* thread) {
  715. ReadOptions options;
  716. std::string value;
  717. int found = 0;
  718. for (int i = 0; i < reads_; i++) {
  719. char key[100];
  720. const int k = thread->rand.Next() % FLAGS_num;
  721. snprintf(key, sizeof(key), "%016d", k);
  722. if (db_->Get(options, key, &value).ok()) {
  723. found++;
  724. }
  725. thread->stats.FinishedSingleOp();
  726. }
  727. char msg[100];
  728. snprintf(msg, sizeof(msg), "(%d of %d found)", found, num_);
  729. thread->stats.AddMessage(msg);
  730. }
  731. void ReadMissing(ThreadState* thread) {
  732. ReadOptions options;
  733. std::string value;
  734. for (int i = 0; i < reads_; i++) {
  735. char key[100];
  736. const int k = thread->rand.Next() % FLAGS_num;
  737. snprintf(key, sizeof(key), "%016d.", k);
  738. db_->Get(options, key, &value);
  739. thread->stats.FinishedSingleOp();
  740. }
  741. }
  742. void ReadHot(ThreadState* thread) {
  743. ReadOptions options;
  744. std::string value;
  745. const int range = (FLAGS_num + 99) / 100;
  746. for (int i = 0; i < reads_; i++) {
  747. char key[100];
  748. const int k = thread->rand.Next() % range;
  749. snprintf(key, sizeof(key), "%016d", k);
  750. db_->Get(options, key, &value);
  751. thread->stats.FinishedSingleOp();
  752. }
  753. }
  754. void SeekRandom(ThreadState* thread) {
  755. ReadOptions options;
  756. int found = 0;
  757. for (int i = 0; i < reads_; i++) {
  758. Iterator* iter = db_->NewIterator(options);
  759. char key[100];
  760. const int k = thread->rand.Next() % FLAGS_num;
  761. snprintf(key, sizeof(key), "%016d", k);
  762. iter->Seek(key);
  763. if (iter->Valid() && iter->key() == key) found++;
  764. delete iter;
  765. thread->stats.FinishedSingleOp();
  766. }
  767. char msg[100];
  768. snprintf(msg, sizeof(msg), "(%d of %d found)", found, num_);
  769. thread->stats.AddMessage(msg);
  770. }
  771. void DoDelete(ThreadState* thread, bool seq) {
  772. RandomGenerator gen;
  773. WriteBatch batch;
  774. Status s;
  775. for (int i = 0; i < num_; i += entries_per_batch_) {
  776. batch.Clear();
  777. for (int j = 0; j < entries_per_batch_; j++) {
  778. const int k = seq ? i+j : (thread->rand.Next() % FLAGS_num);
  779. char key[100];
  780. snprintf(key, sizeof(key), "%016d", k);
  781. batch.Delete(key);
  782. thread->stats.FinishedSingleOp();
  783. }
  784. s = db_->Write(write_options_, &batch);
  785. if (!s.ok()) {
  786. fprintf(stderr, "del error: %s\n", s.ToString().c_str());
  787. exit(1);
  788. }
  789. }
  790. }
  791. void DeleteSeq(ThreadState* thread) {
  792. DoDelete(thread, true);
  793. }
  794. void DeleteRandom(ThreadState* thread) {
  795. DoDelete(thread, false);
  796. }
  797. void ReadWhileWriting(ThreadState* thread) {
  798. if (thread->tid > 0) {
  799. ReadRandom(thread);
  800. } else {
  801. // Special thread that keeps writing until other threads are done.
  802. RandomGenerator gen;
  803. while (true) {
  804. {
  805. MutexLock l(&thread->shared->mu);
  806. if (thread->shared->num_done + 1 >= thread->shared->num_initialized) {
  807. // Other threads have finished
  808. break;
  809. }
  810. }
  811. const int k = thread->rand.Next() % FLAGS_num;
  812. char key[100];
  813. snprintf(key, sizeof(key), "%016d", k);
  814. Status s = db_->Put(write_options_, key, gen.Generate(value_size_));
  815. if (!s.ok()) {
  816. fprintf(stderr, "put error: %s\n", s.ToString().c_str());
  817. exit(1);
  818. }
  819. }
  820. // Do not count any of the preceding work/delay in stats.
  821. thread->stats.Start();
  822. }
  823. }
  824. void Compact(ThreadState* thread) {
  825. db_->CompactRange(NULL, NULL);
  826. }
  827. void PrintStats(const char* key) {
  828. std::string stats;
  829. if (!db_->GetProperty(key, &stats)) {
  830. stats = "(failed)";
  831. }
  832. fprintf(stdout, "\n%s\n", stats.c_str());
  833. }
  834. static void WriteToFile(void* arg, const char* buf, int n) {
  835. reinterpret_cast<WritableFile*>(arg)->Append(Slice(buf, n));
  836. }
  837. void HeapProfile() {
  838. char fname[100];
  839. snprintf(fname, sizeof(fname), "%s/heap-%04d", FLAGS_db, ++heap_counter_);
  840. WritableFile* file;
  841. Status s = g_env->NewWritableFile(fname, &file);
  842. if (!s.ok()) {
  843. fprintf(stderr, "%s\n", s.ToString().c_str());
  844. return;
  845. }
  846. bool ok = port::GetHeapProfile(WriteToFile, file);
  847. delete file;
  848. if (!ok) {
  849. fprintf(stderr, "heap profiling not supported\n");
  850. g_env->DeleteFile(fname);
  851. }
  852. }
  853. };
  854. } // namespace leveldb
  855. int main(int argc, char** argv) {
  856. FLAGS_write_buffer_size = leveldb::Options().write_buffer_size;
  857. FLAGS_max_file_size = leveldb::Options().max_file_size;
  858. FLAGS_block_size = leveldb::Options().block_size;
  859. FLAGS_open_files = leveldb::Options().max_open_files;
  860. std::string default_db_path;
  861. for (int i = 1; i < argc; i++) {
  862. double d;
  863. int n;
  864. char junk;
  865. if (leveldb::Slice(argv[i]).starts_with("--benchmarks=")) {
  866. FLAGS_benchmarks = argv[i] + strlen("--benchmarks=");
  867. } else if (sscanf(argv[i], "--compression_ratio=%lf%c", &d, &junk) == 1) {
  868. FLAGS_compression_ratio = d;
  869. } else if (sscanf(argv[i], "--histogram=%d%c", &n, &junk) == 1 &&
  870. (n == 0 || n == 1)) {
  871. FLAGS_histogram = n;
  872. } else if (sscanf(argv[i], "--use_existing_db=%d%c", &n, &junk) == 1 &&
  873. (n == 0 || n == 1)) {
  874. FLAGS_use_existing_db = n;
  875. } else if (sscanf(argv[i], "--reuse_logs=%d%c", &n, &junk) == 1 &&
  876. (n == 0 || n == 1)) {
  877. FLAGS_reuse_logs = n;
  878. } else if (sscanf(argv[i], "--num=%d%c", &n, &junk) == 1) {
  879. FLAGS_num = n;
  880. } else if (sscanf(argv[i], "--reads=%d%c", &n, &junk) == 1) {
  881. FLAGS_reads = n;
  882. } else if (sscanf(argv[i], "--threads=%d%c", &n, &junk) == 1) {
  883. FLAGS_threads = n;
  884. } else if (sscanf(argv[i], "--value_size=%d%c", &n, &junk) == 1) {
  885. FLAGS_value_size = n;
  886. } else if (sscanf(argv[i], "--write_buffer_size=%d%c", &n, &junk) == 1) {
  887. FLAGS_write_buffer_size = n;
  888. } else if (sscanf(argv[i], "--max_file_size=%d%c", &n, &junk) == 1) {
  889. FLAGS_max_file_size = n;
  890. } else if (sscanf(argv[i], "--block_size=%d%c", &n, &junk) == 1) {
  891. FLAGS_block_size = n;
  892. } else if (sscanf(argv[i], "--cache_size=%d%c", &n, &junk) == 1) {
  893. FLAGS_cache_size = n;
  894. } else if (sscanf(argv[i], "--bloom_bits=%d%c", &n, &junk) == 1) {
  895. FLAGS_bloom_bits = n;
  896. } else if (sscanf(argv[i], "--open_files=%d%c", &n, &junk) == 1) {
  897. FLAGS_open_files = n;
  898. } else if (strncmp(argv[i], "--db=", 5) == 0) {
  899. FLAGS_db = argv[i] + 5;
  900. } else {
  901. fprintf(stderr, "Invalid flag '%s'\n", argv[i]);
  902. exit(1);
  903. }
  904. }
  905. leveldb::g_env = leveldb::Env::Default();
  906. // Choose a location for the test database if none given with --db=<path>
  907. if (FLAGS_db == NULL) {
  908. leveldb::g_env->GetTestDirectory(&default_db_path);
  909. default_db_path += "/dbbench";
  910. FLAGS_db = default_db_path.c_str();
  911. }
  912. leveldb::Benchmark benchmark;
  913. benchmark.Run();
  914. return 0;
  915. }