Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

494 рядки
14 KiB

  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 "include/cache.h"
  10. #include "include/db.h"
  11. #include "include/env.h"
  12. #include "include/write_batch.h"
  13. #include "util/histogram.h"
  14. #include "util/random.h"
  15. #include "util/testutil.h"
  16. // Comma-separated list of operations to run in the specified order
  17. // Actual benchmarks:
  18. // fillseq -- write N values in sequential key order in async mode
  19. // fillrandom -- write N values in random key order in async mode
  20. // overwrite -- overwrite N values in random key order in async mode
  21. // fillsync -- write N/100 values in random key order in sync mode
  22. // fill100K -- write N/1000 100K values in random order in async mode
  23. // readseq -- read N values sequentially
  24. // readreverse -- read N values in reverse order
  25. // readrandom -- read N values in random order
  26. // Meta operations:
  27. // compact -- Compact the entire DB
  28. // heapprofile -- Dump a heap profile (if supported by this port)
  29. // sync -- switch to synchronous writes (not the default)
  30. // nosync -- switch to asynchronous writes (the default)
  31. // tenth -- divide N by 10 (i.e., following benchmarks are smaller)
  32. // normal -- reset N back to its normal value (1000000)
  33. static const char* FLAGS_benchmarks =
  34. "fillseq,"
  35. "fillrandom,"
  36. "overwrite,"
  37. "fillsync,"
  38. "readseq,"
  39. "readreverse,"
  40. "readrandom,"
  41. "compact,"
  42. "readseq,"
  43. "readreverse,"
  44. "readrandom,"
  45. "fill100K";
  46. // Number of key/values to place in database
  47. static int FLAGS_num = 1000000;
  48. // Size of each value
  49. static int FLAGS_value_size = 100;
  50. // Arrange to generate values that shrink to this fraction of
  51. // their original size after compression
  52. static double FLAGS_compression_ratio = 0.5;
  53. // Print histogram of operation timings
  54. static bool FLAGS_histogram = false;
  55. // Number of bytes to buffer in memtable before compacting
  56. static int FLAGS_write_buffer_size = 1 << 20;
  57. namespace leveldb {
  58. // Helper for quickly generating random data.
  59. namespace {
  60. class RandomGenerator {
  61. private:
  62. std::string data_;
  63. int pos_;
  64. public:
  65. RandomGenerator() {
  66. // We use a limited amount of data over and over again and ensure
  67. // that it is larger than the compression window (32KB), and also
  68. // large enough to serve all typical value sizes we want to write.
  69. Random rnd(301);
  70. std::string piece;
  71. while (data_.size() < 1048576) {
  72. // Add a short fragment that is as compressible as specified
  73. // by FLAGS_compression_ratio.
  74. test::CompressibleString(&rnd, FLAGS_compression_ratio, 100, &piece);
  75. data_.append(piece);
  76. }
  77. pos_ = 0;
  78. }
  79. Slice Generate(int len) {
  80. if (pos_ + len > data_.size()) {
  81. pos_ = 0;
  82. assert(len < data_.size());
  83. }
  84. pos_ += len;
  85. return Slice(data_.data() + pos_ - len, len);
  86. }
  87. };
  88. static Slice TrimSpace(Slice s) {
  89. int start = 0;
  90. while (start < s.size() && isspace(s[start])) {
  91. start++;
  92. }
  93. int limit = s.size();
  94. while (limit > start && isspace(s[limit-1])) {
  95. limit--;
  96. }
  97. return Slice(s.data() + start, limit - start);
  98. }
  99. }
  100. class Benchmark {
  101. private:
  102. Cache* cache_;
  103. DB* db_;
  104. int num_;
  105. int heap_counter_;
  106. double start_;
  107. double last_op_finish_;
  108. int64_t bytes_;
  109. std::string message_;
  110. Histogram hist_;
  111. RandomGenerator gen_;
  112. Random rand_;
  113. // State kept for progress messages
  114. int done_;
  115. int next_report_; // When to report next
  116. void PrintHeader() {
  117. const int kKeySize = 16;
  118. PrintEnvironment();
  119. fprintf(stdout, "Keys: %d bytes each\n", kKeySize);
  120. fprintf(stdout, "Values: %d bytes each (%d bytes after compression)\n",
  121. FLAGS_value_size,
  122. static_cast<int>(FLAGS_value_size * FLAGS_compression_ratio + 0.5));
  123. fprintf(stdout, "Entries: %d\n", num_);
  124. fprintf(stdout, "RawSize: %.1f MB (estimated)\n",
  125. (((kKeySize + FLAGS_value_size) * num_) / 1048576.0));
  126. fprintf(stdout, "FileSize: %.1f MB (estimated)\n",
  127. (((kKeySize + FLAGS_value_size * FLAGS_compression_ratio) * num_)
  128. / 1048576.0));
  129. PrintWarnings();
  130. fprintf(stdout, "------------------------------------------------\n");
  131. }
  132. void PrintWarnings() {
  133. #if defined(__GNUC__) && !defined(__OPTIMIZE__)
  134. fprintf(stdout,
  135. "WARNING: Optimization is disabled: benchmarks unnecessarily slow\n"
  136. );
  137. #endif
  138. #ifndef NDEBUG
  139. fprintf(stdout,
  140. "WARNING: Assertions are enabled; benchmarks unnecessarily slow\n");
  141. #endif
  142. }
  143. void PrintEnvironment() {
  144. fprintf(stderr, "LevelDB: version %d.%d\n",
  145. kMajorVersion, kMinorVersion);
  146. #if defined(__linux)
  147. time_t now = time(NULL);
  148. fprintf(stderr, "Date: %s", ctime(&now)); // ctime() adds newline
  149. FILE* cpuinfo = fopen("/proc/cpuinfo", "r");
  150. if (cpuinfo != NULL) {
  151. char line[1000];
  152. int num_cpus = 0;
  153. std::string cpu_type;
  154. std::string cache_size;
  155. while (fgets(line, sizeof(line), cpuinfo) != NULL) {
  156. const char* sep = strchr(line, ':');
  157. if (sep == NULL) {
  158. continue;
  159. }
  160. Slice key = TrimSpace(Slice(line, sep - 1 - line));
  161. Slice val = TrimSpace(Slice(sep + 1));
  162. if (key == "model name") {
  163. ++num_cpus;
  164. cpu_type = val.ToString();
  165. } else if (key == "cache size") {
  166. cache_size = val.ToString();
  167. }
  168. }
  169. fclose(cpuinfo);
  170. fprintf(stderr, "CPU: %d * %s\n", num_cpus, cpu_type.c_str());
  171. fprintf(stderr, "CPUCache: %s\n", cache_size.c_str());
  172. }
  173. #endif
  174. }
  175. void Start() {
  176. start_ = Env::Default()->NowMicros() * 1e-6;
  177. bytes_ = 0;
  178. message_.clear();
  179. last_op_finish_ = start_;
  180. hist_.Clear();
  181. done_ = 0;
  182. next_report_ = 100;
  183. }
  184. void FinishedSingleOp() {
  185. if (FLAGS_histogram) {
  186. double now = Env::Default()->NowMicros() * 1e-6;
  187. double micros = (now - last_op_finish_) * 1e6;
  188. hist_.Add(micros);
  189. if (micros > 20000) {
  190. fprintf(stderr, "long op: %.1f micros%30s\r", micros, "");
  191. fflush(stderr);
  192. }
  193. last_op_finish_ = now;
  194. }
  195. done_++;
  196. if (done_ >= next_report_) {
  197. if (next_report_ < 1000) {
  198. next_report_ += 100;
  199. } else if (next_report_ < 10000) {
  200. next_report_ += 1000;
  201. } else if (next_report_ < 100000) {
  202. next_report_ += 10000;
  203. } else {
  204. next_report_ += 100000;
  205. }
  206. fprintf(stderr, "... finished %d ops%30s\r", done_, "");
  207. fflush(stderr);
  208. }
  209. }
  210. void Stop(const Slice& name) {
  211. double finish = Env::Default()->NowMicros() * 1e-6;
  212. // Pretend at least one op was done in case we are running a benchmark
  213. // that does nto call FinishedSingleOp().
  214. if (done_ < 1) done_ = 1;
  215. if (bytes_ > 0) {
  216. char rate[100];
  217. snprintf(rate, sizeof(rate), "%5.1f MB/s",
  218. (bytes_ / 1048576.0) / (finish - start_));
  219. if (!message_.empty()) {
  220. message_ = std::string(rate) + " " + message_;
  221. } else {
  222. message_ = rate;
  223. }
  224. }
  225. fprintf(stdout, "%-12s : %11.3f micros/op;%s%s\n",
  226. name.ToString().c_str(),
  227. (finish - start_) * 1e6 / done_,
  228. (message_.empty() ? "" : " "),
  229. message_.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. public:
  236. enum Order {
  237. SEQUENTIAL,
  238. RANDOM
  239. };
  240. enum DBState {
  241. FRESH,
  242. EXISTING
  243. };
  244. Benchmark() : cache_(NewLRUCache(200<<20)),
  245. db_(NULL),
  246. num_(FLAGS_num),
  247. heap_counter_(0),
  248. bytes_(0),
  249. rand_(301) {
  250. std::vector<std::string> files;
  251. Env::Default()->GetChildren("/tmp/dbbench", &files);
  252. for (int i = 0; i < files.size(); i++) {
  253. if (Slice(files[i]).starts_with("heap-")) {
  254. Env::Default()->DeleteFile("/tmp/dbbench/" + files[i]);
  255. }
  256. }
  257. DestroyDB("/tmp/dbbench", Options());
  258. }
  259. ~Benchmark() {
  260. delete db_;
  261. delete cache_;
  262. }
  263. void Run() {
  264. PrintHeader();
  265. Open();
  266. const char* benchmarks = FLAGS_benchmarks;
  267. while (benchmarks != NULL) {
  268. const char* sep = strchr(benchmarks, ',');
  269. Slice name;
  270. if (sep == NULL) {
  271. name = benchmarks;
  272. benchmarks = NULL;
  273. } else {
  274. name = Slice(benchmarks, sep - benchmarks);
  275. benchmarks = sep + 1;
  276. }
  277. Start();
  278. WriteOptions write_options;
  279. write_options.sync = false;
  280. if (name == Slice("fillseq")) {
  281. Write(write_options, SEQUENTIAL, FRESH, num_, FLAGS_value_size);
  282. } else if (name == Slice("fillrandom")) {
  283. Write(write_options, RANDOM, FRESH, num_, FLAGS_value_size);
  284. } else if (name == Slice("overwrite")) {
  285. Write(write_options, RANDOM, EXISTING, num_, FLAGS_value_size);
  286. } else if (name == Slice("fillsync")) {
  287. write_options.sync = true;
  288. Write(write_options, RANDOM, FRESH, num_ / 100, FLAGS_value_size);
  289. } else if (name == Slice("fill100K")) {
  290. Write(write_options, RANDOM, FRESH, num_ / 1000, 100 * 1000);
  291. } else if (name == Slice("readseq")) {
  292. ReadSequential();
  293. } else if (name == Slice("readreverse")) {
  294. ReadReverse();
  295. } else if (name == Slice("readrandom")) {
  296. ReadRandom();
  297. } else if (name == Slice("compact")) {
  298. Compact();
  299. } else if (name == Slice("heapprofile")) {
  300. HeapProfile();
  301. } else {
  302. fprintf(stderr, "unknown benchmark '%s'\n", name.ToString().c_str());
  303. }
  304. Stop(name);
  305. }
  306. }
  307. private:
  308. void Open() {
  309. assert(db_ == NULL);
  310. Options options;
  311. options.create_if_missing = true;
  312. options.max_open_files = 10000;
  313. options.block_cache = cache_;
  314. options.write_buffer_size = FLAGS_write_buffer_size;
  315. Status s = DB::Open(options, "/tmp/dbbench", &db_);
  316. if (!s.ok()) {
  317. fprintf(stderr, "open error: %s\n", s.ToString().c_str());
  318. exit(1);
  319. }
  320. }
  321. void Write(const WriteOptions& options, Order order, DBState state,
  322. int num_entries, int value_size) {
  323. if (state == FRESH) {
  324. delete db_;
  325. db_ = NULL;
  326. DestroyDB("/tmp/dbbench", Options());
  327. Open();
  328. Start(); // Do not count time taken to destroy/open
  329. }
  330. if (num_entries != num_) {
  331. char msg[100];
  332. snprintf(msg, sizeof(msg), "(%d ops)", num_entries);
  333. message_ = msg;
  334. }
  335. WriteBatch batch;
  336. Status s;
  337. std::string val;
  338. for (int i = 0; i < num_entries; i++) {
  339. const int k = (order == SEQUENTIAL) ? i : (rand_.Next() % FLAGS_num);
  340. char key[100];
  341. snprintf(key, sizeof(key), "%016d", k);
  342. batch.Clear();
  343. batch.Put(key, gen_.Generate(value_size));
  344. s = db_->Write(options, &batch);
  345. bytes_ += value_size + strlen(key);
  346. if (!s.ok()) {
  347. fprintf(stderr, "put error: %s\n", s.ToString().c_str());
  348. exit(1);
  349. }
  350. FinishedSingleOp();
  351. }
  352. }
  353. void ReadSequential() {
  354. Iterator* iter = db_->NewIterator(ReadOptions());
  355. int i = 0;
  356. for (iter->SeekToFirst(); i < num_ && iter->Valid(); iter->Next()) {
  357. bytes_ += iter->key().size() + iter->value().size();
  358. FinishedSingleOp();
  359. ++i;
  360. }
  361. delete iter;
  362. }
  363. void ReadReverse() {
  364. Iterator* iter = db_->NewIterator(ReadOptions());
  365. int i = 0;
  366. for (iter->SeekToLast(); i < num_ && iter->Valid(); iter->Prev()) {
  367. bytes_ += iter->key().size() + iter->value().size();
  368. FinishedSingleOp();
  369. ++i;
  370. }
  371. delete iter;
  372. }
  373. void ReadRandom() {
  374. ReadOptions options;
  375. std::string value;
  376. for (int i = 0; i < num_; i++) {
  377. char key[100];
  378. const int k = rand_.Next() % FLAGS_num;
  379. snprintf(key, sizeof(key), "%016d", k);
  380. db_->Get(options, key, &value);
  381. FinishedSingleOp();
  382. }
  383. }
  384. void Compact() {
  385. DBImpl* dbi = reinterpret_cast<DBImpl*>(db_);
  386. dbi->TEST_CompactMemTable();
  387. int max_level_with_files = 1;
  388. for (int level = 1; level < config::kNumLevels; level++) {
  389. uint64_t v;
  390. char name[100];
  391. snprintf(name, sizeof(name), "leveldb.num-files-at-level%d", level);
  392. if (db_->GetProperty(name, &v) && v > 0) {
  393. max_level_with_files = level;
  394. }
  395. }
  396. for (int level = 0; level < max_level_with_files; level++) {
  397. dbi->TEST_CompactRange(level, "", "~");
  398. }
  399. }
  400. static void WriteToFile(void* arg, const char* buf, int n) {
  401. reinterpret_cast<WritableFile*>(arg)->Append(Slice(buf, n));
  402. }
  403. void HeapProfile() {
  404. char fname[100];
  405. snprintf(fname, sizeof(fname), "/tmp/dbbench/heap-%04d", ++heap_counter_);
  406. WritableFile* file;
  407. Status s = Env::Default()->NewWritableFile(fname, &file);
  408. if (!s.ok()) {
  409. message_ = s.ToString();
  410. return;
  411. }
  412. bool ok = port::GetHeapProfile(WriteToFile, file);
  413. delete file;
  414. if (!ok) {
  415. message_ = "not supported";
  416. Env::Default()->DeleteFile(fname);
  417. }
  418. }
  419. };
  420. }
  421. int main(int argc, char** argv) {
  422. for (int i = 1; i < argc; i++) {
  423. double d;
  424. int n;
  425. char junk;
  426. if (leveldb::Slice(argv[i]).starts_with("--benchmarks=")) {
  427. FLAGS_benchmarks = argv[i] + strlen("--benchmarks=");
  428. } else if (sscanf(argv[i], "--compression_ratio=%lf%c", &d, &junk) == 1) {
  429. FLAGS_compression_ratio = d;
  430. } else if (sscanf(argv[i], "--histogram=%d%c", &n, &junk) == 1 &&
  431. (n == 0 || n == 1)) {
  432. FLAGS_histogram = n;
  433. } else if (sscanf(argv[i], "--num=%d%c", &n, &junk) == 1) {
  434. FLAGS_num = n;
  435. } else if (sscanf(argv[i], "--value_size=%d%c", &n, &junk) == 1) {
  436. FLAGS_value_size = n;
  437. } else if (sscanf(argv[i], "--write_buffer_size=%d%c", &n, &junk) == 1) {
  438. FLAGS_write_buffer_size = n;
  439. } else {
  440. fprintf(stderr, "Invalid flag '%s'\n", argv[i]);
  441. exit(1);
  442. }
  443. }
  444. leveldb::Benchmark benchmark;
  445. benchmark.Run();
  446. return 0;
  447. }