Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

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