FSTLevelDBBenchmarkTests.mm 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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/Model/FSTDocumentKey.h"
  23. #import "Firestore/Source/Remote/FSTSerializerBeta.h"
  24. #include "Firestore/core/src/firebase/firestore/local/leveldb_key.h"
  25. #include "Firestore/core/src/firebase/firestore/local/leveldb_transaction.h"
  26. #include "Firestore/core/src/firebase/firestore/model/types.h"
  27. NS_ASSUME_NONNULL_BEGIN
  28. using firebase::firestore::local::LevelDbTargetDocumentKey;
  29. using firebase::firestore::local::LevelDbTransaction;
  30. using firebase::firestore::model::DatabaseId;
  31. using firebase::firestore::model::TargetId;
  32. namespace {
  33. // Pre-existing document size
  34. const int kDocumentSize = 1024 * 2; // 2 kb
  35. std::string DocumentData() {
  36. return std::string(kDocumentSize, 'a');
  37. }
  38. std::string UpdatedDocumentData(int64_t documentSize) {
  39. return std::string(documentSize, 'b');
  40. }
  41. NSString *LevelDBDir() {
  42. NSFileManager *files = [NSFileManager defaultManager];
  43. NSString *dir =
  44. [NSTemporaryDirectory() stringByAppendingPathComponent:@"FSTPersistenceTestHelpers"];
  45. if ([files fileExistsAtPath:dir]) {
  46. // Delete the directory first to ensure isolation between runs.
  47. NSError *error;
  48. BOOL success = [files removeItemAtPath:dir error:&error];
  49. if (!success) {
  50. [NSException raise:NSInternalInconsistencyException
  51. format:@"Failed to clean up leveldb path %@: %@", dir, error];
  52. }
  53. }
  54. return dir;
  55. }
  56. FSTLevelDB *LevelDBPersistence() {
  57. // This owns the DatabaseIds since we do not have FirestoreClient instance to own them.
  58. static DatabaseId database_id{"p", "d"};
  59. NSString *dir = LevelDBDir();
  60. FSTSerializerBeta *remoteSerializer = [[FSTSerializerBeta alloc] initWithDatabaseID:&database_id];
  61. FSTLocalSerializer *serializer =
  62. [[FSTLocalSerializer alloc] initWithRemoteSerializer:remoteSerializer];
  63. FSTLevelDB *db = [[FSTLevelDB alloc] initWithDirectory:dir serializer:serializer];
  64. NSError *error;
  65. BOOL success = [db start:&error];
  66. if (!success) {
  67. [NSException raise:NSInternalInconsistencyException
  68. format:@"Failed to create leveldb path %@: %@", dir, error];
  69. }
  70. return db;
  71. }
  72. } // namespace
  73. class LevelDBFixture : public benchmark::Fixture {
  74. void SetUp(benchmark::State &state) override {
  75. db_ = LevelDBPersistence();
  76. FillDB();
  77. }
  78. void TearDown(benchmark::State &state) override {
  79. db_ = nil;
  80. }
  81. void FillDB() {
  82. LevelDbTransaction txn(db_.ptr, "benchmark");
  83. for (int i = 0; i < numDocuments_; i++) {
  84. FSTDocumentKey *docKey =
  85. [FSTDocumentKey keyWithPathString:[NSString stringWithFormat:@"docs/doc_%i", i]];
  86. std::string docKeyString = [FSTLevelDBRemoteDocumentKey keyWithDocumentKey: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, FSTDocumentKey *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) {
  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. FSTDocumentKey *docKey =
  117. [FSTDocumentKey keyWithPathString:[NSString stringWithFormat:@"docs/doc_%i", i]];
  118. if (writeIndexes) WriteIndex(txn, docKey);
  119. std::string docKeyString = [FSTLevelDBRemoteDocumentKey keyWithDocumentKey:docKey];
  120. txn.Put(docKeyString, documentUpdate);
  121. }
  122. txn.Commit();
  123. }
  124. }
  125. /**
  126. * Adjust ranges to control what test cases run. Outermost loop controls whether or
  127. * not indexes are written, the inner loops control size of document writes and number
  128. * of document writes.
  129. */
  130. static void TestCases(benchmark::internal::Benchmark *b) {
  131. for (int writeIndexes = 0; writeIndexes <= 1; writeIndexes++) {
  132. for (int documentSize = 1 << 10; documentSize <= 1 << 20; documentSize *= 4) {
  133. for (int docsToUpdate = 1; docsToUpdate <= 5; docsToUpdate++) {
  134. b->Args({writeIndexes, documentSize, docsToUpdate});
  135. }
  136. }
  137. }
  138. }
  139. BENCHMARK_REGISTER_F(LevelDBFixture, RemoteEvent)
  140. ->Apply(TestCases)
  141. ->Unit(benchmark::kMicrosecond)
  142. ->Repetitions(5);
  143. @interface FSTLevelDBBenchmarkTests : XCTestCase
  144. @end
  145. @implementation FSTLevelDBBenchmarkTests
  146. - (void)testRunBenchmarks {
  147. // Enable to run benchmarks.
  148. char *argv[3] = {const_cast<char *>("Benchmarks"),
  149. const_cast<char *>("--benchmark_out=/tmp/leveldb_benchmark"),
  150. const_cast<char *>("--benchmark_out_format=csv")};
  151. int argc = 3;
  152. benchmark::Initialize(&argc, argv);
  153. benchmark::RunSpecifiedBenchmarks();
  154. }
  155. @end
  156. NS_ASSUME_NONNULL_END