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.
8 #include "util/histogram.h"
9 #include "util/random.h"
10 #include "util/testutil.h"
12 // Comma-separated list of operations to run in the specified order
15 // fillseq -- write N values in sequential key order in async mode
16 // fillrandom -- write N values in random key order in async mode
17 // overwrite -- overwrite N values in random key order in async mode
18 // fillseqsync -- write N/100 values in sequential key order in sync mode
19 // fillrandsync -- write N/100 values in random key order in sync mode
20 // fillrand100K -- write N/1000 100K values in random order in async mode
21 // fillseq100K -- write N/1000 100K values in seq order in async mode
22 // readseq -- read N times sequentially
23 // readseq100K -- read N/1000 100K values in sequential order in async mode
24 // readrand100K -- read N/1000 100K values in sequential order in async mode
25 // readrandom -- read N times in random order
26 static const char* FLAGS_benchmarks =
40 // Number of key/values to place in database
41 static int FLAGS_num = 1000000;
43 // Number of read operations to do. If negative, do FLAGS_num reads.
44 static int FLAGS_reads = -1;
47 static int FLAGS_value_size = 100;
49 // Arrange to generate values that shrink to this fraction of
50 // their original size after compression
51 static double FLAGS_compression_ratio = 0.5;
53 // Print histogram of operation timings
54 static bool FLAGS_histogram = false;
56 // Cache size. Default 4 MB
57 static int FLAGS_cache_size = 4194304;
59 // Page size. Default 1 KB
60 static int FLAGS_page_size = 1024;
62 // If true, do not destroy the existing database. If you set this
63 // flag and also specify a benchmark that wants a fresh database, that
64 // benchmark will fail.
65 static bool FLAGS_use_existing_db = false;
67 // Compression flag. If true, compression is on. If false, compression
69 static bool FLAGS_compression = true;
71 // Use the db with the following name.
72 static const char* FLAGS_db = NULL;
75 static void DBSynchronize(kyotocabinet::TreeDB* db_)
77 // Synchronize will flush writes to disk
78 if (!db_->synchronize()) {
79 fprintf(stderr, "synchronize error: %s\n", db_->error().name());
85 // Helper for quickly generating random data.
87 class RandomGenerator {
94 // We use a limited amount of data over and over again and ensure
95 // that it is larger than the compression window (32KB), and also
96 // large enough to serve all typical value sizes we want to write.
99 while (data_.size() < 1048576) {
100 // Add a short fragment that is as compressible as specified
101 // by FLAGS_compression_ratio.
102 test::CompressibleString(&rnd, FLAGS_compression_ratio, 100, &piece);
108 Slice Generate(int len) {
109 if (pos_ + len > data_.size()) {
111 assert(len < data_.size());
114 return Slice(data_.data() + pos_ - len, len);
118 static Slice TrimSpace(Slice s) {
120 while (start < s.size() && isspace(s[start])) {
123 int limit = s.size();
124 while (limit > start && isspace(s[limit-1])) {
127 return Slice(s.data() + start, limit - start);
134 kyotocabinet::TreeDB* db_;
139 double last_op_finish_;
141 std::string message_;
143 RandomGenerator gen_;
145 kyotocabinet::LZOCompressor<kyotocabinet::LZO::RAW> comp_;
147 // State kept for progress messages
149 int next_report_; // When to report next
152 const int kKeySize = 16;
154 fprintf(stdout, "Keys: %d bytes each\n", kKeySize);
155 fprintf(stdout, "Values: %d bytes each (%d bytes after compression)\n",
157 static_cast<int>(FLAGS_value_size * FLAGS_compression_ratio + 0.5));
158 fprintf(stdout, "Entries: %d\n", num_);
159 fprintf(stdout, "RawSize: %.1f MB (estimated)\n",
160 ((static_cast<int64_t>(kKeySize + FLAGS_value_size) * num_)
162 fprintf(stdout, "FileSize: %.1f MB (estimated)\n",
163 (((kKeySize + FLAGS_value_size * FLAGS_compression_ratio) * num_)
166 fprintf(stdout, "------------------------------------------------\n");
169 void PrintWarnings() {
170 #if defined(__GNUC__) && !defined(__OPTIMIZE__)
172 "WARNING: Optimization is disabled: benchmarks unnecessarily slow\n"
177 "WARNING: Assertions are enabled; benchmarks unnecessarily slow\n");
181 void PrintEnvironment() {
182 fprintf(stderr, "Kyoto Cabinet: version %s, lib ver %d, lib rev %d\n",
183 kyotocabinet::VERSION, kyotocabinet::LIBVER, kyotocabinet::LIBREV);
186 time_t now = time(NULL);
187 fprintf(stderr, "Date: %s", ctime(&now)); // ctime() adds newline
189 FILE* cpuinfo = fopen("/proc/cpuinfo", "r");
190 if (cpuinfo != NULL) {
193 std::string cpu_type;
194 std::string cache_size;
195 while (fgets(line, sizeof(line), cpuinfo) != NULL) {
196 const char* sep = strchr(line, ':');
200 Slice key = TrimSpace(Slice(line, sep - 1 - line));
201 Slice val = TrimSpace(Slice(sep + 1));
202 if (key == "model name") {
204 cpu_type = val.ToString();
205 } else if (key == "cache size") {
206 cache_size = val.ToString();
210 fprintf(stderr, "CPU: %d * %s\n", num_cpus, cpu_type.c_str());
211 fprintf(stderr, "CPUCache: %s\n", cache_size.c_str());
217 start_ = Env::Default()->NowMicros() * 1e-6;
220 last_op_finish_ = start_;
226 void FinishedSingleOp() {
227 if (FLAGS_histogram) {
228 double now = Env::Default()->NowMicros() * 1e-6;
229 double micros = (now - last_op_finish_) * 1e6;
231 if (micros > 20000) {
232 fprintf(stderr, "long op: %.1f micros%30s\r", micros, "");
235 last_op_finish_ = now;
239 if (done_ >= next_report_) {
240 if (next_report_ < 1000) next_report_ += 100;
241 else if (next_report_ < 5000) next_report_ += 500;
242 else if (next_report_ < 10000) next_report_ += 1000;
243 else if (next_report_ < 50000) next_report_ += 5000;
244 else if (next_report_ < 100000) next_report_ += 10000;
245 else if (next_report_ < 500000) next_report_ += 50000;
246 else next_report_ += 100000;
247 fprintf(stderr, "... finished %d ops%30s\r", done_, "");
252 void Stop(const Slice& name) {
253 double finish = Env::Default()->NowMicros() * 1e-6;
255 // Pretend at least one op was done in case we are running a benchmark
256 // that does not call FinishedSingleOp().
257 if (done_ < 1) done_ = 1;
261 snprintf(rate, sizeof(rate), "%6.1f MB/s",
262 (bytes_ / 1048576.0) / (finish - start_));
263 if (!message_.empty()) {
264 message_ = std::string(rate) + " " + message_;
270 fprintf(stdout, "%-12s : %11.3f micros/op;%s%s\n",
271 name.ToString().c_str(),
272 (finish - start_) * 1e6 / done_,
273 (message_.empty() ? "" : " "),
275 if (FLAGS_histogram) {
276 fprintf(stdout, "Microseconds per op:\n%s\n", hist_.ToString().c_str());
294 reads_(FLAGS_reads < 0 ? FLAGS_num : FLAGS_reads),
297 std::vector<std::string> files;
298 std::string test_dir;
299 Env::Default()->GetTestDirectory(&test_dir);
300 Env::Default()->GetChildren(test_dir.c_str(), &files);
301 if (!FLAGS_use_existing_db) {
302 for (int i = 0; i < files.size(); i++) {
303 if (Slice(files[i]).starts_with("dbbench_polyDB")) {
304 std::string file_name(test_dir);
306 file_name += files[i];
307 Env::Default()->DeleteFile(file_name.c_str());
315 fprintf(stderr, "close error: %s\n", db_->error().name());
323 const char* benchmarks = FLAGS_benchmarks;
324 while (benchmarks != NULL) {
325 const char* sep = strchr(benchmarks, ',');
331 name = Slice(benchmarks, sep - benchmarks);
332 benchmarks = sep + 1;
338 bool write_sync = false;
339 if (name == Slice("fillseq")) {
340 Write(write_sync, SEQUENTIAL, FRESH, num_, FLAGS_value_size, 1);
342 } else if (name == Slice("fillrandom")) {
343 Write(write_sync, RANDOM, FRESH, num_, FLAGS_value_size, 1);
345 } else if (name == Slice("overwrite")) {
346 Write(write_sync, RANDOM, EXISTING, num_, FLAGS_value_size, 1);
348 } else if (name == Slice("fillrandsync")) {
350 Write(write_sync, RANDOM, FRESH, num_ / 100, FLAGS_value_size, 1);
352 } else if (name == Slice("fillseqsync")) {
354 Write(write_sync, SEQUENTIAL, FRESH, num_ / 100, FLAGS_value_size, 1);
356 } else if (name == Slice("fillrand100K")) {
357 Write(write_sync, RANDOM, FRESH, num_ / 1000, 100 * 1000, 1);
359 } else if (name == Slice("fillseq100K")) {
360 Write(write_sync, SEQUENTIAL, FRESH, num_ / 1000, 100 * 1000, 1);
362 } else if (name == Slice("readseq")) {
364 } else if (name == Slice("readrandom")) {
366 } else if (name == Slice("readrand100K")) {
371 } else if (name == Slice("readseq100K")) {
378 if (name != Slice()) { // No error message for empty name
379 fprintf(stderr, "unknown benchmark '%s'\n", name.ToString().c_str());
389 void Open(bool sync) {
393 db_ = new kyotocabinet::TreeDB();
396 std::string test_dir;
397 Env::Default()->GetTestDirectory(&test_dir);
398 snprintf(file_name, sizeof(file_name),
399 "%s/dbbench_polyDB-%d.kct",
403 // Create tuning options and open the database
404 int open_options = kyotocabinet::PolyDB::OWRITER |
405 kyotocabinet::PolyDB::OCREATE;
406 int tune_options = kyotocabinet::TreeDB::TSMALL |
407 kyotocabinet::TreeDB::TLINEAR;
408 if (FLAGS_compression) {
409 tune_options |= kyotocabinet::TreeDB::TCOMPRESS;
410 db_->tune_compressor(&comp_);
412 db_->tune_options(tune_options);
413 db_->tune_page_cache(FLAGS_cache_size);
414 db_->tune_page(FLAGS_page_size);
415 db_->tune_map(256LL<<20);
417 open_options |= kyotocabinet::PolyDB::OAUTOSYNC;
419 if (!db_->open(file_name, open_options)) {
420 fprintf(stderr, "open error: %s\n", db_->error().name());
424 void Write(bool sync, Order order, DBState state,
425 int num_entries, int value_size, int entries_per_batch) {
426 // Create new database if state == FRESH
427 if (state == FRESH) {
428 if (FLAGS_use_existing_db) {
429 message_ = "skipping (--use_existing_db is true)";
435 Start(); // Do not count time taken to destroy/open
438 if (num_entries != num_) {
440 snprintf(msg, sizeof(msg), "(%d ops)", num_entries);
445 for (int i = 0; i < num_entries; i++)
447 const int k = (order == SEQUENTIAL) ? i : (rand_.Next() % num_entries);
449 snprintf(key, sizeof(key), "%016d", k);
450 bytes_ += value_size + strlen(key);
451 std::string cpp_key = key;
452 if (!db_->set(cpp_key, gen_.Generate(value_size).ToString())) {
453 fprintf(stderr, "set error: %s\n", db_->error().name());
459 void ReadSequential() {
460 kyotocabinet::DB::Cursor* cur = db_->cursor();
462 std::string ckey, cvalue;
463 while (cur->get(&ckey, &cvalue, true)) {
464 bytes_ += ckey.size() + cvalue.size();
472 for (int i = 0; i < reads_; i++) {
474 const int k = rand_.Next() % reads_;
475 snprintf(key, sizeof(key), "%016d", k);
476 db_->get(key, &value);
482 } // namespace leveldb
484 int main(int argc, char** argv) {
485 std::string default_db_path;
486 for (int i = 1; i < argc; i++) {
490 if (leveldb::Slice(argv[i]).starts_with("--benchmarks=")) {
491 FLAGS_benchmarks = argv[i] + strlen("--benchmarks=");
492 } else if (sscanf(argv[i], "--compression_ratio=%lf%c", &d, &junk) == 1) {
493 FLAGS_compression_ratio = d;
494 } else if (sscanf(argv[i], "--histogram=%d%c", &n, &junk) == 1 &&
495 (n == 0 || n == 1)) {
497 } else if (sscanf(argv[i], "--num=%d%c", &n, &junk) == 1) {
499 } else if (sscanf(argv[i], "--reads=%d%c", &n, &junk) == 1) {
501 } else if (sscanf(argv[i], "--value_size=%d%c", &n, &junk) == 1) {
502 FLAGS_value_size = n;
503 } else if (sscanf(argv[i], "--cache_size=%d%c", &n, &junk) == 1) {
504 FLAGS_cache_size = n;
505 } else if (sscanf(argv[i], "--page_size=%d%c", &n, &junk) == 1) {
507 } else if (sscanf(argv[i], "--compression=%d%c", &n, &junk) == 1 &&
508 (n == 0 || n == 1)) {
509 FLAGS_compression = (n == 1) ? true : false;
510 } else if (strncmp(argv[i], "--db=", 5) == 0) {
511 FLAGS_db = argv[i] + 5;
513 fprintf(stderr, "Invalid flag '%s'\n", argv[i]);
518 // Choose a location for the test database if none given with --db=<path>
519 if (FLAGS_db == NULL) {
520 leveldb::Env::Default()->GetTestDirectory(&default_db_path);
521 default_db_path += "/dbbench";
522 FLAGS_db = default_db_path.c_str();
525 leveldb::Benchmark benchmark;