FSTLevelDBBenchmarkTests.mm 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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. #include "benchmark/benchmark.h"
  20. #import "Firestore/Source/Local/FSTLevelDB.h"
  21. #import "Firestore/Source/Local/FSTLocalSerializer.h"
  22. #import "Firestore/Source/Remote/FSTSerializerBeta.h"
  23. #include "Firestore/core/src/firebase/firestore/local/leveldb_key.h"
  24. #include "Firestore/core/src/firebase/firestore/local/leveldb_transaction.h"
  25. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  26. #include "Firestore/core/src/firebase/firestore/model/types.h"
  27. #include "Firestore/core/src/firebase/firestore/util/string_format.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. // This owns the DatabaseIds since we do not have FirestoreClient instance to own them.
  62. static DatabaseId database_id{"p", "d"};
  63. NSString *dir = LevelDBDir();
  64. FSTSerializerBeta *remoteSerializer = [[FSTSerializerBeta alloc] initWithDatabaseID:&database_id];
  65. FSTLocalSerializer *serializer =
  66. [[FSTLocalSerializer alloc] initWithRemoteSerializer:remoteSerializer];
  67. FSTLevelDB *db = [[FSTLevelDB alloc] initWithDirectory:dir serializer:serializer];
  68. NSError *error;
  69. BOOL success = [db start:&error];
  70. if (!success) {
  71. [NSException raise:NSInternalInconsistencyException
  72. format:@"Failed to create leveldb path %@: %@", dir, error];
  73. }
  74. return db;
  75. }
  76. } // namespace
  77. class LevelDBFixture : public benchmark::Fixture {
  78. void SetUp(benchmark::State &state) override {
  79. db_ = LevelDBPersistence();
  80. FillDB();
  81. }
  82. void TearDown(benchmark::State &state) override {
  83. db_ = nil;
  84. }
  85. void FillDB() {
  86. LevelDbTransaction txn(db_.ptr, "benchmark");
  87. for (int i = 0; i < numDocuments_; i++) {
  88. auto docKey = DocumentKey::FromPathString(StringFormat("docs/doc_%i", i));
  89. std::string docKeyString = LevelDbRemoteDocumentKey::Key(docKey);
  90. txn.Put(docKeyString, DocumentData());
  91. WriteIndex(txn, docKey);
  92. }
  93. txn.Commit();
  94. // Force a write to disk to simulate startup situation
  95. db_.ptr->CompactRange(NULL, NULL);
  96. }
  97. protected:
  98. void WriteIndex(LevelDbTransaction &txn, const DocumentKey &docKey) {
  99. // Arbitrary target ID
  100. TargetId targetID = 1;
  101. txn.Put(LevelDbDocumentTargetKey::Key(docKey, targetID), emptyBuffer_);
  102. txn.Put(LevelDbTargetDocumentKey::Key(targetID, docKey), emptyBuffer_);
  103. }
  104. FSTLevelDB *db_;
  105. int numDocuments_ = 10;
  106. std::string emptyBuffer_;
  107. };
  108. // Plan: write a bunch of key/value pairs w/ empty strings (index entries)
  109. // Write a couple large values (documents)
  110. // In each test, either overwrite index entries and documents, or just documents
  111. BENCHMARK_DEFINE_F(LevelDBFixture, RemoteEvent)(benchmark::State &state) {
  112. bool writeIndexes = static_cast<bool>(state.range(0));
  113. int64_t documentSize = state.range(1);
  114. int64_t docsToUpdate = state.range(2);
  115. std::string documentUpdate = UpdatedDocumentData(documentSize);
  116. for (const auto &_ : state) {
  117. LevelDbTransaction txn(db_.ptr, "benchmark");
  118. for (int i = 0; i < docsToUpdate; i++) {
  119. auto docKey = DocumentKey::FromPathString(StringFormat("docs/doc_%i", i));
  120. if (writeIndexes) WriteIndex(txn, docKey);
  121. std::string docKeyString = LevelDbRemoteDocumentKey::Key(docKey);
  122. txn.Put(docKeyString, documentUpdate);
  123. }
  124. txn.Commit();
  125. }
  126. }
  127. /**
  128. * Adjust ranges to control what test cases run. Outermost loop controls whether or
  129. * not indexes are written, the inner loops control size of document writes and number
  130. * of document writes.
  131. */
  132. static void TestCases(benchmark::internal::Benchmark *b) {
  133. for (int writeIndexes = 0; writeIndexes <= 1; writeIndexes++) {
  134. for (int documentSize = 1 << 10; documentSize <= 1 << 20; documentSize *= 4) {
  135. for (int docsToUpdate = 1; docsToUpdate <= 5; docsToUpdate++) {
  136. b->Args({writeIndexes, documentSize, docsToUpdate});
  137. }
  138. }
  139. }
  140. }
  141. BENCHMARK_REGISTER_F(LevelDBFixture, RemoteEvent)
  142. ->Apply(TestCases)
  143. ->Unit(benchmark::kMicrosecond)
  144. ->Repetitions(5);
  145. @interface FSTLevelDBBenchmarkTests : XCTestCase
  146. @end
  147. @implementation FSTLevelDBBenchmarkTests
  148. - (void)testRunBenchmarks {
  149. // Enable to run benchmarks.
  150. char *argv[3] = {const_cast<char *>("Benchmarks"),
  151. const_cast<char *>("--benchmark_out=/tmp/leveldb_benchmark"),
  152. const_cast<char *>("--benchmark_out_format=csv")};
  153. int argc = 3;
  154. benchmark::Initialize(&argc, argv);
  155. benchmark::RunSpecifiedBenchmarks();
  156. }
  157. @end
  158. NS_ASSUME_NONNULL_END