小组成员: 曹可心-10223903406 朴祉燕-10224602413
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

522 lines
16 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 years ago
  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 <kcpolydb.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include "util/histogram.h"
  8. #include "util/random.h"
  9. #include "util/testutil.h"
  10. // Comma-separated list of operations to run in the specified order
  11. // Actual benchmarks:
  12. //
  13. // fillseq -- write N values in sequential key order in async mode
  14. // fillrandom -- write N values in random key order in async mode
  15. // overwrite -- overwrite N values in random key order in async mode
  16. // fillseqsync -- write N/100 values in sequential key order in sync mode
  17. // fillrandsync -- write N/100 values in random key order in sync mode
  18. // fillrand100K -- write N/1000 100K values in random order in async mode
  19. // fillseq100K -- write N/1000 100K values in seq order in async mode
  20. // readseq -- read N times sequentially
  21. // readseq100K -- read N/1000 100K values in sequential order in async mode
  22. // readrand100K -- read N/1000 100K values in sequential order in async mode
  23. // readrandom -- read N times in random order
  24. static const char* FLAGS_benchmarks =
  25. "fillseq,"
  26. "fillseqsync,"
  27. "fillrandsync,"
  28. "fillrandom,"
  29. "overwrite,"
  30. "readrandom,"
  31. "readseq,"
  32. "fillrand100K,"
  33. "fillseq100K,"
  34. "readseq100K,"
  35. "readrand100K,";
  36. // Number of key/values to place in database
  37. static int FLAGS_num = 1000000;
  38. // Number of read operations to do. If negative, do FLAGS_num reads.
  39. static int FLAGS_reads = -1;
  40. // Size of each value
  41. static int FLAGS_value_size = 100;
  42. // Arrange to generate values that shrink to this fraction of
  43. // their original size after compression
  44. static double FLAGS_compression_ratio = 0.5;
  45. // Print histogram of operation timings
  46. static bool FLAGS_histogram = false;
  47. // Cache size. Default 4 MB
  48. static int FLAGS_cache_size = 4194304;
  49. // Page size. Default 1 KB
  50. static int FLAGS_page_size = 1024;
  51. // If true, do not destroy the existing database. If you set this
  52. // flag and also specify a benchmark that wants a fresh database, that
  53. // benchmark will fail.
  54. static bool FLAGS_use_existing_db = false;
  55. // Compression flag. If true, compression is on. If false, compression
  56. // is off.
  57. static bool FLAGS_compression = true;
  58. // Use the db with the following name.
  59. static const char* FLAGS_db = nullptr;
  60. inline static void DBSynchronize(kyotocabinet::TreeDB* db_) {
  61. // Synchronize will flush writes to disk
  62. if (!db_->synchronize()) {
  63. fprintf(stderr, "synchronize error: %s\n", db_->error().name());
  64. }
  65. }
  66. namespace leveldb {
  67. // Helper for quickly generating random data.
  68. namespace {
  69. class RandomGenerator {
  70. private:
  71. std::string data_;
  72. int pos_;
  73. public:
  74. RandomGenerator() {
  75. // We use a limited amount of data over and over again and ensure
  76. // that it is larger than the compression window (32KB), and also
  77. // large enough to serve all typical value sizes we want to write.
  78. Random rnd(301);
  79. std::string piece;
  80. while (data_.size() < 1048576) {
  81. // Add a short fragment that is as compressible as specified
  82. // by FLAGS_compression_ratio.
  83. test::CompressibleString(&rnd, FLAGS_compression_ratio, 100, &piece);
  84. data_.append(piece);
  85. }
  86. pos_ = 0;
  87. }
  88. Slice Generate(int len) {
  89. if (pos_ + len > data_.size()) {
  90. pos_ = 0;
  91. assert(len < data_.size());
  92. }
  93. pos_ += len;
  94. return Slice(data_.data() + pos_ - len, len);
  95. }
  96. };
  97. static Slice TrimSpace(Slice s) {
  98. int start = 0;
  99. while (start < s.size() && isspace(s[start])) {
  100. start++;
  101. }
  102. int limit = s.size();
  103. while (limit > start && isspace(s[limit - 1])) {
  104. limit--;
  105. }
  106. return Slice(s.data() + start, limit - start);
  107. }
  108. } // namespace
  109. class Benchmark {
  110. private:
  111. kyotocabinet::TreeDB* db_;
  112. int db_num_;
  113. int num_;
  114. int reads_;
  115. double start_;
  116. double last_op_finish_;
  117. int64_t bytes_;
  118. std::string message_;
  119. Histogram hist_;
  120. RandomGenerator gen_;
  121. Random rand_;
  122. kyotocabinet::LZOCompressor<kyotocabinet::LZO::RAW> comp_;
  123. // State kept for progress messages
  124. int done_;
  125. int next_report_; // When to report next
  126. void PrintHeader() {
  127. const int kKeySize = 16;
  128. PrintEnvironment();
  129. fprintf(stdout, "Keys: %d bytes each\n", kKeySize);
  130. fprintf(stdout, "Values: %d bytes each (%d bytes after compression)\n",
  131. FLAGS_value_size,
  132. static_cast<int>(FLAGS_value_size * FLAGS_compression_ratio + 0.5));
  133. fprintf(stdout, "Entries: %d\n", num_);
  134. fprintf(stdout, "RawSize: %.1f MB (estimated)\n",
  135. ((static_cast<int64_t>(kKeySize + FLAGS_value_size) * num_) /
  136. 1048576.0));
  137. fprintf(stdout, "FileSize: %.1f MB (estimated)\n",
  138. (((kKeySize + FLAGS_value_size * FLAGS_compression_ratio) * num_) /
  139. 1048576.0));
  140. PrintWarnings();
  141. fprintf(stdout, "------------------------------------------------\n");
  142. }
  143. void PrintWarnings() {
  144. #if defined(__GNUC__) && !defined(__OPTIMIZE__)
  145. fprintf(
  146. stdout,
  147. "WARNING: Optimization is disabled: benchmarks unnecessarily slow\n");
  148. #endif
  149. #ifndef NDEBUG
  150. fprintf(stdout,
  151. "WARNING: Assertions are enabled; benchmarks unnecessarily slow\n");
  152. #endif
  153. }
  154. void PrintEnvironment() {
  155. fprintf(stderr, "Kyoto Cabinet: version %s, lib ver %d, lib rev %d\n",
  156. kyotocabinet::VERSION, kyotocabinet::LIBVER, kyotocabinet::LIBREV);
  157. #if defined(__linux)
  158. time_t now = time(nullptr);
  159. fprintf(stderr, "Date: %s", ctime(&now)); // ctime() adds newline
  160. FILE* cpuinfo = fopen("/proc/cpuinfo", "r");
  161. if (cpuinfo != nullptr) {
  162. char line[1000];
  163. int num_cpus = 0;
  164. std::string cpu_type;
  165. std::string cache_size;
  166. while (fgets(line, sizeof(line), cpuinfo) != nullptr) {
  167. const char* sep = strchr(line, ':');
  168. if (sep == nullptr) {
  169. continue;
  170. }
  171. Slice key = TrimSpace(Slice(line, sep - 1 - line));
  172. Slice val = TrimSpace(Slice(sep + 1));
  173. if (key == "model name") {
  174. ++num_cpus;
  175. cpu_type = val.ToString();
  176. } else if (key == "cache size") {
  177. cache_size = val.ToString();
  178. }
  179. }
  180. fclose(cpuinfo);
  181. fprintf(stderr, "CPU: %d * %s\n", num_cpus, cpu_type.c_str());
  182. fprintf(stderr, "CPUCache: %s\n", cache_size.c_str());
  183. }
  184. #endif
  185. }
  186. void Start() {
  187. start_ = Env::Default()->NowMicros() * 1e-6;
  188. bytes_ = 0;
  189. message_.clear();
  190. last_op_finish_ = start_;
  191. hist_.Clear();
  192. done_ = 0;
  193. next_report_ = 100;
  194. }
  195. void FinishedSingleOp() {
  196. if (FLAGS_histogram) {
  197. double now = Env::Default()->NowMicros() * 1e-6;
  198. double micros = (now - last_op_finish_) * 1e6;
  199. hist_.Add(micros);
  200. if (micros > 20000) {
  201. fprintf(stderr, "long op: %.1f micros%30s\r", micros, "");
  202. fflush(stderr);
  203. }
  204. last_op_finish_ = now;
  205. }
  206. done_++;
  207. if (done_ >= next_report_) {
  208. if (next_report_ < 1000)
  209. next_report_ += 100;
  210. else if (next_report_ < 5000)
  211. next_report_ += 500;
  212. else if (next_report_ < 10000)
  213. next_report_ += 1000;
  214. else if (next_report_ < 50000)
  215. next_report_ += 5000;
  216. else if (next_report_ < 100000)
  217. next_report_ += 10000;
  218. else if (next_report_ < 500000)
  219. next_report_ += 50000;
  220. else
  221. next_report_ += 100000;
  222. fprintf(stderr, "... finished %d ops%30s\r", done_, "");
  223. fflush(stderr);
  224. }
  225. }
  226. void Stop(const Slice& name) {
  227. double finish = Env::Default()->NowMicros() * 1e-6;
  228. // Pretend at least one op was done in case we are running a benchmark
  229. // that does not call FinishedSingleOp().
  230. if (done_ < 1) done_ = 1;
  231. if (bytes_ > 0) {
  232. char rate[100];
  233. snprintf(rate, sizeof(rate), "%6.1f MB/s",
  234. (bytes_ / 1048576.0) / (finish - start_));
  235. if (!message_.empty()) {
  236. message_ = std::string(rate) + " " + message_;
  237. } else {
  238. message_ = rate;
  239. }
  240. }
  241. fprintf(stdout, "%-12s : %11.3f micros/op;%s%s\n", name.ToString().c_str(),
  242. (finish - start_) * 1e6 / done_, (message_.empty() ? "" : " "),
  243. message_.c_str());
  244. if (FLAGS_histogram) {
  245. fprintf(stdout, "Microseconds per op:\n%s\n", hist_.ToString().c_str());
  246. }
  247. fflush(stdout);
  248. }
  249. public:
  250. enum Order { SEQUENTIAL, RANDOM };
  251. enum DBState { FRESH, EXISTING };
  252. Benchmark()
  253. : db_(nullptr),
  254. num_(FLAGS_num),
  255. reads_(FLAGS_reads < 0 ? FLAGS_num : FLAGS_reads),
  256. bytes_(0),
  257. rand_(301) {
  258. std::vector<std::string> files;
  259. std::string test_dir;
  260. Env::Default()->GetTestDirectory(&test_dir);
  261. Env::Default()->GetChildren(test_dir.c_str(), &files);
  262. if (!FLAGS_use_existing_db) {
  263. for (int i = 0; i < files.size(); i++) {
  264. if (Slice(files[i]).starts_with("dbbench_polyDB")) {
  265. std::string file_name(test_dir);
  266. file_name += "/";
  267. file_name += files[i];
  268. Env::Default()->DeleteFile(file_name.c_str());
  269. }
  270. }
  271. }
  272. }
  273. ~Benchmark() {
  274. if (!db_->close()) {
  275. fprintf(stderr, "close error: %s\n", db_->error().name());
  276. }
  277. }
  278. void Run() {
  279. PrintHeader();
  280. Open(false);
  281. const char* benchmarks = FLAGS_benchmarks;
  282. while (benchmarks != nullptr) {
  283. const char* sep = strchr(benchmarks, ',');
  284. Slice name;
  285. if (sep == nullptr) {
  286. name = benchmarks;
  287. benchmarks = nullptr;
  288. } else {
  289. name = Slice(benchmarks, sep - benchmarks);
  290. benchmarks = sep + 1;
  291. }
  292. Start();
  293. bool known = true;
  294. bool write_sync = false;
  295. if (name == Slice("fillseq")) {
  296. Write(write_sync, SEQUENTIAL, FRESH, num_, FLAGS_value_size, 1);
  297. DBSynchronize(db_);
  298. } else if (name == Slice("fillrandom")) {
  299. Write(write_sync, RANDOM, FRESH, num_, FLAGS_value_size, 1);
  300. DBSynchronize(db_);
  301. } else if (name == Slice("overwrite")) {
  302. Write(write_sync, RANDOM, EXISTING, num_, FLAGS_value_size, 1);
  303. DBSynchronize(db_);
  304. } else if (name == Slice("fillrandsync")) {
  305. write_sync = true;
  306. Write(write_sync, RANDOM, FRESH, num_ / 100, FLAGS_value_size, 1);
  307. DBSynchronize(db_);
  308. } else if (name == Slice("fillseqsync")) {
  309. write_sync = true;
  310. Write(write_sync, SEQUENTIAL, FRESH, num_ / 100, FLAGS_value_size, 1);
  311. DBSynchronize(db_);
  312. } else if (name == Slice("fillrand100K")) {
  313. Write(write_sync, RANDOM, FRESH, num_ / 1000, 100 * 1000, 1);
  314. DBSynchronize(db_);
  315. } else if (name == Slice("fillseq100K")) {
  316. Write(write_sync, SEQUENTIAL, FRESH, num_ / 1000, 100 * 1000, 1);
  317. DBSynchronize(db_);
  318. } else if (name == Slice("readseq")) {
  319. ReadSequential();
  320. } else if (name == Slice("readrandom")) {
  321. ReadRandom();
  322. } else if (name == Slice("readrand100K")) {
  323. int n = reads_;
  324. reads_ /= 1000;
  325. ReadRandom();
  326. reads_ = n;
  327. } else if (name == Slice("readseq100K")) {
  328. int n = reads_;
  329. reads_ /= 1000;
  330. ReadSequential();
  331. reads_ = n;
  332. } else {
  333. known = false;
  334. if (name != Slice()) { // No error message for empty name
  335. fprintf(stderr, "unknown benchmark '%s'\n", name.ToString().c_str());
  336. }
  337. }
  338. if (known) {
  339. Stop(name);
  340. }
  341. }
  342. }
  343. private:
  344. void Open(bool sync) {
  345. assert(db_ == nullptr);
  346. // Initialize db_
  347. db_ = new kyotocabinet::TreeDB();
  348. char file_name[100];
  349. db_num_++;
  350. std::string test_dir;
  351. Env::Default()->GetTestDirectory(&test_dir);
  352. snprintf(file_name, sizeof(file_name), "%s/dbbench_polyDB-%d.kct",
  353. test_dir.c_str(), db_num_);
  354. // Create tuning options and open the database
  355. int open_options =
  356. kyotocabinet::PolyDB::OWRITER | kyotocabinet::PolyDB::OCREATE;
  357. int tune_options =
  358. kyotocabinet::TreeDB::TSMALL | kyotocabinet::TreeDB::TLINEAR;
  359. if (FLAGS_compression) {
  360. tune_options |= kyotocabinet::TreeDB::TCOMPRESS;
  361. db_->tune_compressor(&comp_);
  362. }
  363. db_->tune_options(tune_options);
  364. db_->tune_page_cache(FLAGS_cache_size);
  365. db_->tune_page(FLAGS_page_size);
  366. db_->tune_map(256LL << 20);
  367. if (sync) {
  368. open_options |= kyotocabinet::PolyDB::OAUTOSYNC;
  369. }
  370. if (!db_->open(file_name, open_options)) {
  371. fprintf(stderr, "open error: %s\n", db_->error().name());
  372. }
  373. }
  374. void Write(bool sync, Order order, DBState state, int num_entries,
  375. int value_size, int entries_per_batch) {
  376. // Create new database if state == FRESH
  377. if (state == FRESH) {
  378. if (FLAGS_use_existing_db) {
  379. message_ = "skipping (--use_existing_db is true)";
  380. return;
  381. }
  382. delete db_;
  383. db_ = nullptr;
  384. Open(sync);
  385. Start(); // Do not count time taken to destroy/open
  386. }
  387. if (num_entries != num_) {
  388. char msg[100];
  389. snprintf(msg, sizeof(msg), "(%d ops)", num_entries);
  390. message_ = msg;
  391. }
  392. // Write to database
  393. for (int i = 0; i < num_entries; i++) {
  394. const int k = (order == SEQUENTIAL) ? i : (rand_.Next() % num_entries);
  395. char key[100];
  396. snprintf(key, sizeof(key), "%016d", k);
  397. bytes_ += value_size + strlen(key);
  398. std::string cpp_key = key;
  399. if (!db_->set(cpp_key, gen_.Generate(value_size).ToString())) {
  400. fprintf(stderr, "set error: %s\n", db_->error().name());
  401. }
  402. FinishedSingleOp();
  403. }
  404. }
  405. void ReadSequential() {
  406. kyotocabinet::DB::Cursor* cur = db_->cursor();
  407. cur->jump();
  408. std::string ckey, cvalue;
  409. while (cur->get(&ckey, &cvalue, true)) {
  410. bytes_ += ckey.size() + cvalue.size();
  411. FinishedSingleOp();
  412. }
  413. delete cur;
  414. }
  415. void ReadRandom() {
  416. std::string value;
  417. for (int i = 0; i < reads_; i++) {
  418. char key[100];
  419. const int k = rand_.Next() % reads_;
  420. snprintf(key, sizeof(key), "%016d", k);
  421. db_->get(key, &value);
  422. FinishedSingleOp();
  423. }
  424. }
  425. };
  426. } // namespace leveldb
  427. int main(int argc, char** argv) {
  428. std::string default_db_path;
  429. for (int i = 1; i < argc; i++) {
  430. double d;
  431. int n;
  432. char junk;
  433. if (leveldb::Slice(argv[i]).starts_with("--benchmarks=")) {
  434. FLAGS_benchmarks = argv[i] + strlen("--benchmarks=");
  435. } else if (sscanf(argv[i], "--compression_ratio=%lf%c", &d, &junk) == 1) {
  436. FLAGS_compression_ratio = d;
  437. } else if (sscanf(argv[i], "--histogram=%d%c", &n, &junk) == 1 &&
  438. (n == 0 || n == 1)) {
  439. FLAGS_histogram = n;
  440. } else if (sscanf(argv[i], "--num=%d%c", &n, &junk) == 1) {
  441. FLAGS_num = n;
  442. } else if (sscanf(argv[i], "--reads=%d%c", &n, &junk) == 1) {
  443. FLAGS_reads = n;
  444. } else if (sscanf(argv[i], "--value_size=%d%c", &n, &junk) == 1) {
  445. FLAGS_value_size = n;
  446. } else if (sscanf(argv[i], "--cache_size=%d%c", &n, &junk) == 1) {
  447. FLAGS_cache_size = n;
  448. } else if (sscanf(argv[i], "--page_size=%d%c", &n, &junk) == 1) {
  449. FLAGS_page_size = n;
  450. } else if (sscanf(argv[i], "--compression=%d%c", &n, &junk) == 1 &&
  451. (n == 0 || n == 1)) {
  452. FLAGS_compression = (n == 1) ? true : false;
  453. } else if (strncmp(argv[i], "--db=", 5) == 0) {
  454. FLAGS_db = argv[i] + 5;
  455. } else {
  456. fprintf(stderr, "Invalid flag '%s'\n", argv[i]);
  457. exit(1);
  458. }
  459. }
  460. // Choose a location for the test database if none given with --db=<path>
  461. if (FLAGS_db == nullptr) {
  462. leveldb::Env::Default()->GetTestDirectory(&default_db_path);
  463. default_db_path += "/dbbench";
  464. FLAGS_db = default_db_path.c_str();
  465. }
  466. leveldb::Benchmark benchmark;
  467. benchmark.Run();
  468. return 0;
  469. }