作者: 韩晨旭 10225101440 李畅 10225102463
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

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