FSTLevelDBBenchmarkTests.mm 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. /*
  2. * Copyright 2018 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import <Foundation/Foundation.h>
  17. #import <XCTest/XCTest.h>
  18. #include <cstdint>
  19. #import "Firestore/Source/Local/FSTLevelDB.h"
  20. #import "Firestore/Source/Local/FSTLocalSerializer.h"
  21. #import "Firestore/Source/Remote/FSTSerializerBeta.h"
  22. #include "Firestore/core/src/firebase/firestore/local/leveldb_key.h"
  23. #include "Firestore/core/src/firebase/firestore/local/leveldb_transaction.h"
  24. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  25. #include "Firestore/core/src/firebase/firestore/model/types.h"
  26. #include "Firestore/core/src/firebase/firestore/util/string_format.h"
  27. #include "benchmark/benchmark.h"
  28. NS_ASSUME_NONNULL_BEGIN
  29. using firebase::firestore::local::LevelDbRemoteDocumentKey;
  30. using firebase::firestore::local::LevelDbTargetDocumentKey;
  31. using firebase::firestore::local::LevelDbTransaction;
  32. using firebase::firestore::model::DatabaseId;
  33. using firebase::firestore::model::DocumentKey;
  34. using firebase::firestore::model::TargetId;
  35. using firebase::firestore::util::StringFormat;
  36. namespace {
  37. // Pre-existing document size
  38. const int kDocumentSize = 1024 * 2; // 2 kb
  39. std::string DocumentData() {
  40. return std::string(kDocumentSize, 'a');
  41. }
  42. std::string UpdatedDocumentData(int64_t documentSize) {
  43. return std::string(documentSize, 'b');
  44. }
  45. NSString *LevelDBDir() {
  46. NSFileManager *files = [NSFileManager defaultManager];
  47. NSString *dir =
  48. [NSTemporaryDirectory() stringByAppendingPathComponent:@"FSTPersistenceTestHelpers"];
  49. if ([files fileExistsAtPath:dir]) {
  50. // Delete the directory first to ensure isolation between runs.
  51. NSError *error;
  52. BOOL success = [files removeItemAtPath:dir error:&error];
  53. if (!success) {
  54. [NSException raise:NSInternalInconsistencyException
  55. format:@"Failed to clean up leveldb path %@: %@", dir, error];
  56. }
  57. }
  58. return dir;
  59. }
  60. FSTLevelDB *LevelDBPersistence() {
  61. NSString *dir = LevelDBDir();
  62. auto remoteSerializer = [[FSTSerializerBeta alloc] initWithDatabaseID:DatabaseId("p", "d")];
  63. auto serializer = [[FSTLocalSerializer alloc] initWithRemoteSerializer:remoteSerializer];
  64. auto db = [[FSTLevelDB alloc] initWithDirectory:dir serializer:serializer];
  65. NSError *error;
  66. BOOL success = [db start:&error];
  67. if (!success) {
  68. [NSException raise:NSInternalInconsistencyException
  69. format:@"Failed to create leveldb path %@: %@", dir, error];
  70. }
  71. return db;
  72. }
  73. } // namespace
  74. class LevelDBFixture : public benchmark::Fixture {
  75. void SetUp(benchmark::State &state) override {
  76. db_ = LevelDBPersistence();
  77. FillDB();
  78. }
  79. void TearDown(benchmark::State &state) override {
  80. db_ = nil;
  81. }
  82. void FillDB() {
  83. LevelDbTransaction txn(db_.ptr, "benchmark");
  84. for (int i = 0; i < numDocuments_; i++) {
  85. auto docKey = DocumentKey::FromPathString(StringFormat("docs/doc_%i", i));
  86. std::string docKeyString = LevelDbRemoteDocumentKey::Key(docKey);
  87. txn.Put(docKeyString, DocumentData());
  88. WriteIndex(&txn, docKey);
  89. }
  90. txn.Commit();
  91. // Force a write to disk to simulate startup situation
  92. db_.ptr->CompactRange(NULL, NULL);
  93. }
  94. protected:
  95. void WriteIndex(LevelDbTransaction *txn, const DocumentKey &docKey) {
  96. // Arbitrary target ID
  97. TargetId targetID = 1;
  98. txn->Put(LevelDbDocumentTargetKey::Key(docKey, targetID), emptyBuffer_);
  99. txn->Put(LevelDbTargetDocumentKey::Key(targetID, docKey), emptyBuffer_);
  100. }
  101. FSTLevelDB *db_;
  102. int numDocuments_ = 10;
  103. std::string emptyBuffer_;
  104. };
  105. // Plan: write a bunch of key/value pairs w/ empty strings (index entries)
  106. // Write a couple large values (documents)
  107. // In each test, either overwrite index entries and documents, or just documents
  108. BENCHMARK_DEFINE_F(LevelDBFixture, RemoteEvent)(benchmark::State &state) { // NOLINT
  109. bool writeIndexes = static_cast<bool>(state.range(0));
  110. int64_t documentSize = state.range(1);
  111. int64_t docsToUpdate = state.range(2);
  112. std::string documentUpdate = UpdatedDocumentData(documentSize);
  113. for (const auto &_ : state) {
  114. LevelDbTransaction txn(db_.ptr, "benchmark");
  115. for (int i = 0; i < docsToUpdate; i++) {
  116. auto docKey = DocumentKey::FromPathString(StringFormat("docs/doc_%i", i));
  117. if (writeIndexes) WriteIndex(&txn, docKey);
  118. std::string docKeyString = LevelDbRemoteDocumentKey::Key(docKey);
  119. txn.Put(docKeyString, documentUpdate);
  120. }
  121. txn.Commit();
  122. }
  123. }
  124. /**
  125. * Adjust ranges to control what test cases run. Outermost loop controls whether or
  126. * not indexes are written, the inner loops control size of document writes and number
  127. * of document writes.
  128. */
  129. static void TestCases(benchmark::internal::Benchmark *b) {
  130. for (int writeIndexes = 0; writeIndexes <= 1; writeIndexes++) {
  131. for (int documentSize = 1 << 10; documentSize <= 1 << 20; documentSize *= 4) {
  132. for (int docsToUpdate = 1; docsToUpdate <= 5; docsToUpdate++) {
  133. b->Args({writeIndexes, documentSize, docsToUpdate});
  134. }
  135. }
  136. }
  137. }
  138. BENCHMARK_REGISTER_F(LevelDBFixture, RemoteEvent)
  139. ->Apply(TestCases)
  140. ->Unit(benchmark::kMicrosecond)
  141. ->Repetitions(5);
  142. @interface FSTLevelDBBenchmarkTests : XCTestCase
  143. @end
  144. @implementation FSTLevelDBBenchmarkTests
  145. - (void)testRunBenchmarks {
  146. // Enable to run benchmarks.
  147. char *argv[3] = {const_cast<char *>("Benchmarks"),
  148. const_cast<char *>("--benchmark_out=/tmp/leveldb_benchmark"),
  149. const_cast<char *>("--benchmark_out_format=csv")};
  150. int argc = 3;
  151. benchmark::Initialize(&argc, argv);
  152. benchmark::RunSpecifiedBenchmarks();
  153. }
  154. @end
  155. NS_ASSUME_NONNULL_END