Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

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