forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdisk_cache_perftest.cc
433 lines (354 loc) · 13.9 KB
/
disk_cache_perftest.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <limits>
#include <string>
#include "base/barrier_closure.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/hash.h"
#include "base/process/process_metrics.h"
#include "base/rand_util.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/test/perf_time_logger.h"
#include "base/test/scoped_task_environment.h"
#include "base/test/test_file_util.h"
#include "base/threading/thread.h"
#include "net/base/cache_type.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/base/test_completion_callback.h"
#include "net/disk_cache/backend_cleanup_tracker.h"
#include "net/disk_cache/blockfile/backend_impl.h"
#include "net/disk_cache/blockfile/block_files.h"
#include "net/disk_cache/disk_cache.h"
#include "net/disk_cache/disk_cache_test_base.h"
#include "net/disk_cache/disk_cache_test_util.h"
#include "net/disk_cache/simple/simple_backend_impl.h"
#include "net/disk_cache/simple/simple_index.h"
#include "net/disk_cache/simple/simple_index_file.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"
using base::Time;
namespace {
void MaybeSetFdLimit(unsigned int max_descriptors) {
#if defined(OS_POSIX)
base::SetFdLimit(max_descriptors);
#endif
}
struct TestEntry {
std::string key;
int data_len;
};
class DiskCachePerfTest : public DiskCacheTestWithCache {
public:
DiskCachePerfTest()
: DiskCacheTestWithCache(&scoped_task_environment_),
saved_fd_limit_(base::GetMaxFds()) {
if (saved_fd_limit_ < kFdLimitForCacheTests)
MaybeSetFdLimit(kFdLimitForCacheTests);
}
~DiskCachePerfTest() override {
if (saved_fd_limit_ < kFdLimitForCacheTests)
MaybeSetFdLimit(saved_fd_limit_);
}
protected:
enum class WhatToRead {
HEADERS_ONLY,
HEADERS_AND_BODY,
};
// Helper methods for constructing tests.
bool TimeWrite();
bool TimeRead(WhatToRead what_to_read, const char* timer_message);
void ResetAndEvictSystemDiskCache();
// Complete perf tests.
void CacheBackendPerformance();
const size_t kFdLimitForCacheTests = 8192;
const int kNumEntries = 1000;
const int kHeadersSize = 800;
const int kBodySize = 256 * 1024 - 1;
std::vector<TestEntry> entries_;
private:
const size_t saved_fd_limit_;
base::test::ScopedTaskEnvironment scoped_task_environment_;
};
// Creates num_entries on the cache, and writes kHeaderSize bytes of metadata
// and up to kBodySize of data to each entry.
bool DiskCachePerfTest::TimeWrite() {
// TODO(gavinp): This test would be significantly more realistic if it didn't
// do single reads and writes. Perhaps entries should be written 64kb at a
// time. As well, not all entries should be created and written essentially
// simultaneously; some number of entries in flight at a time would be a
// likely better testing load.
scoped_refptr<net::IOBuffer> buffer1(new net::IOBuffer(kHeadersSize));
scoped_refptr<net::IOBuffer> buffer2(new net::IOBuffer(kBodySize));
CacheTestFillBuffer(buffer1->data(), kHeadersSize, false);
CacheTestFillBuffer(buffer2->data(), kBodySize, false);
int expected = 0;
MessageLoopHelper helper;
CallbackTest callback(&helper, true);
base::PerfTimeLogger timer("Write disk cache entries");
for (int i = 0; i < kNumEntries; i++) {
TestEntry entry;
entry.key = GenerateKey(true);
entry.data_len = base::RandInt(0, kBodySize);
entries_.push_back(entry);
disk_cache::Entry* cache_entry;
net::TestCompletionCallback cb;
int rv = cache_->CreateEntry(entry.key, &cache_entry, cb.callback());
if (net::OK != cb.GetResult(rv))
break;
int ret = cache_entry->WriteData(
0, 0, buffer1.get(), kHeadersSize,
base::Bind(&CallbackTest::Run, base::Unretained(&callback)), false);
if (net::ERR_IO_PENDING == ret)
expected++;
else if (kHeadersSize != ret)
break;
ret = cache_entry->WriteData(
1, 0, buffer2.get(), entry.data_len,
base::Bind(&CallbackTest::Run, base::Unretained(&callback)), false);
if (net::ERR_IO_PENDING == ret)
expected++;
else if (entry.data_len != ret)
break;
cache_entry->Close();
}
helper.WaitUntilCacheIoFinished(expected);
timer.Done();
return expected == helper.callbacks_called();
}
// Reads the data and metadata from each entry listed on |entries|.
bool DiskCachePerfTest::TimeRead(WhatToRead what_to_read,
const char* timer_message) {
scoped_refptr<net::IOBuffer> buffer1(new net::IOBuffer(kHeadersSize));
scoped_refptr<net::IOBuffer> buffer2(new net::IOBuffer(kBodySize));
CacheTestFillBuffer(buffer1->data(), kHeadersSize, false);
CacheTestFillBuffer(buffer2->data(), kBodySize, false);
int expected = 0;
MessageLoopHelper helper;
CallbackTest callback(&helper, true);
base::PerfTimeLogger timer(timer_message);
for (int i = 0; i < kNumEntries; i++) {
disk_cache::Entry* cache_entry;
net::TestCompletionCallback cb;
int rv = cache_->OpenEntry(entries_[i].key, &cache_entry, cb.callback());
if (net::OK != cb.GetResult(rv))
break;
int ret = cache_entry->ReadData(
0, 0, buffer1.get(), kHeadersSize,
base::Bind(&CallbackTest::Run, base::Unretained(&callback)));
if (net::ERR_IO_PENDING == ret)
expected++;
else if (kHeadersSize != ret)
break;
if (what_to_read == WhatToRead::HEADERS_AND_BODY) {
ret = cache_entry->ReadData(
1, 0, buffer2.get(), entries_[i].data_len,
base::Bind(&CallbackTest::Run, base::Unretained(&callback)));
if (net::ERR_IO_PENDING == ret)
expected++;
else if (entries_[i].data_len != ret)
break;
}
cache_entry->Close();
}
helper.WaitUntilCacheIoFinished(expected);
timer.Done();
return (expected == helper.callbacks_called());
}
TEST_F(DiskCachePerfTest, BlockfileHashes) {
base::PerfTimeLogger timer("Hash disk cache keys");
for (int i = 0; i < 300000; i++) {
std::string key = GenerateKey(true);
base::Hash(key);
}
timer.Done();
}
void DiskCachePerfTest::ResetAndEvictSystemDiskCache() {
base::RunLoop().RunUntilIdle();
cache_.reset();
// Flush all files in the cache out of system memory.
const base::FilePath::StringType file_pattern = FILE_PATH_LITERAL("*");
base::FileEnumerator enumerator(cache_path_, true /* recursive */,
base::FileEnumerator::FILES, file_pattern);
for (base::FilePath file_path = enumerator.Next(); !file_path.empty();
file_path = enumerator.Next()) {
ASSERT_TRUE(base::EvictFileFromSystemCache(file_path));
}
#if defined(OS_LINUX) || defined(OS_ANDROID)
// And, cache directories, on platforms where the eviction utility supports
// this (currently Linux and Android only).
if (simple_cache_mode_) {
ASSERT_TRUE(
base::EvictFileFromSystemCache(cache_path_.AppendASCII("index-dir")));
}
ASSERT_TRUE(base::EvictFileFromSystemCache(cache_path_));
#endif
DisableFirstCleanup();
InitCache();
}
void DiskCachePerfTest::CacheBackendPerformance() {
InitCache();
EXPECT_TRUE(TimeWrite());
disk_cache::SimpleBackendImpl::FlushWorkerPoolForTesting();
base::RunLoop().RunUntilIdle();
ResetAndEvictSystemDiskCache();
EXPECT_TRUE(TimeRead(WhatToRead::HEADERS_ONLY,
"Read disk cache headers only (cold)"));
EXPECT_TRUE(TimeRead(WhatToRead::HEADERS_ONLY,
"Read disk cache headers only (warm)"));
disk_cache::SimpleBackendImpl::FlushWorkerPoolForTesting();
base::RunLoop().RunUntilIdle();
ResetAndEvictSystemDiskCache();
EXPECT_TRUE(
TimeRead(WhatToRead::HEADERS_AND_BODY, "Read disk cache entries (cold)"));
EXPECT_TRUE(
TimeRead(WhatToRead::HEADERS_AND_BODY, "Read disk cache entries (warm)"));
disk_cache::SimpleBackendImpl::FlushWorkerPoolForTesting();
base::RunLoop().RunUntilIdle();
}
TEST_F(DiskCachePerfTest, CacheBackendPerformance) {
CacheBackendPerformance();
}
TEST_F(DiskCachePerfTest, SimpleCacheBackendPerformance) {
SetSimpleCacheMode();
CacheBackendPerformance();
}
// Creating and deleting "entries" on a block-file is something quite frequent
// (after all, almost everything is stored on block files). The operation is
// almost free when the file is empty, but can be expensive if the file gets
// fragmented, or if we have multiple files. This test measures that scenario,
// by using multiple, highly fragmented files.
TEST_F(DiskCachePerfTest, BlockFilesPerformance) {
ASSERT_TRUE(CleanupCacheDir());
disk_cache::BlockFiles files(cache_path_);
ASSERT_TRUE(files.Init(true));
const int kNumBlocks = 60000;
disk_cache::Addr address[kNumBlocks];
base::PerfTimeLogger timer1("Fill three block-files");
// Fill up the 32-byte block file (use three files).
for (int i = 0; i < kNumBlocks; i++) {
int block_size = base::RandInt(1, 4);
EXPECT_TRUE(
files.CreateBlock(disk_cache::RANKINGS, block_size, &address[i]));
}
timer1.Done();
base::PerfTimeLogger timer2("Create and delete blocks");
for (int i = 0; i < 200000; i++) {
int block_size = base::RandInt(1, 4);
int entry = base::RandInt(0, kNumBlocks - 1);
files.DeleteBlock(address[entry], false);
EXPECT_TRUE(
files.CreateBlock(disk_cache::RANKINGS, block_size, &address[entry]));
}
timer2.Done();
base::RunLoop().RunUntilIdle();
}
void VerifyRvAndCallClosure(base::Closure* c, int expect_rv, int rv) {
EXPECT_EQ(expect_rv, rv);
c->Run();
}
TEST_F(DiskCachePerfTest, SimpleCacheInitialReadPortion) {
// A benchmark that aims to measure how much time we take in I/O thread
// for initial bookkeeping before returning to the caller, and how much
// after (batched up some). The later portion includes some event loop
// overhead.
const int kBatchSize = 100;
SetSimpleCacheMode();
InitCache();
// Write out the entries, and keep their objects around.
scoped_refptr<net::IOBuffer> buffer1(new net::IOBuffer(kHeadersSize));
scoped_refptr<net::IOBuffer> buffer2(new net::IOBuffer(kBodySize));
CacheTestFillBuffer(buffer1->data(), kHeadersSize, false);
CacheTestFillBuffer(buffer2->data(), kBodySize, false);
disk_cache::Entry* cache_entry[kBatchSize];
for (int i = 0; i < kBatchSize; ++i) {
net::TestCompletionCallback cb;
int rv = cache_->CreateEntry(base::IntToString(i), &cache_entry[i],
cb.callback());
ASSERT_EQ(net::OK, cb.GetResult(rv));
rv = cache_entry[i]->WriteData(0, 0, buffer1.get(), kHeadersSize,
cb.callback(), false);
ASSERT_EQ(kHeadersSize, cb.GetResult(rv));
rv = cache_entry[i]->WriteData(1, 0, buffer2.get(), kBodySize,
cb.callback(), false);
ASSERT_EQ(kBodySize, cb.GetResult(rv));
}
// Now repeatedly read these, batching up the waiting to try to
// account for the two portions separately. Note that we need separate entries
// since we are trying to keep interesting work from being on the delayed-done
// portion.
const int kIterations = 50000;
double elapsed_early = 0.0;
double elapsed_late = 0.0;
for (int i = 0; i < kIterations; ++i) {
base::RunLoop event_loop;
base::Closure barrier =
base::BarrierClosure(kBatchSize, event_loop.QuitWhenIdleClosure());
net::CompletionCallback cb_batch(base::Bind(
VerifyRvAndCallClosure, base::Unretained(&barrier), kHeadersSize));
base::ElapsedTimer timer_early;
for (int e = 0; e < kBatchSize; ++e) {
int rv =
cache_entry[e]->ReadData(0, 0, buffer1.get(), kHeadersSize, cb_batch);
if (rv != net::ERR_IO_PENDING) {
barrier.Run();
ASSERT_EQ(kHeadersSize, rv);
}
}
elapsed_early += timer_early.Elapsed().InMillisecondsF();
base::ElapsedTimer timer_late;
event_loop.Run();
elapsed_late += timer_late.Elapsed().InMillisecondsF();
}
// Cleanup
for (int i = 0; i < kBatchSize; ++i)
cache_entry[i]->Close();
disk_cache::SimpleBackendImpl::FlushWorkerPoolForTesting();
base::RunLoop().RunUntilIdle();
LOG(ERROR) << "Early portion:" << elapsed_early << " ms";
LOG(ERROR) << "\tPer entry:"
<< 1000 * (elapsed_early / (kIterations * kBatchSize)) << " us";
LOG(ERROR) << "Event loop portion: " << elapsed_late << " ms";
LOG(ERROR) << "\tPer entry:"
<< 1000 * (elapsed_late / (kIterations * kBatchSize)) << " us";
}
// Measures how quickly SimpleIndex can compute which entries to evict.
TEST(SimpleIndexPerfTest, EvictionPerformance) {
const int kEntries = 10000;
class NoOpDelegate : public disk_cache::SimpleIndexDelegate {
void DoomEntries(std::vector<uint64_t>* entry_hashes,
const net::CompletionCallback& callback) override {}
};
NoOpDelegate delegate;
base::Time start(base::Time::Now());
double evict_elapsed_ms = 0;
int iterations = 0;
while (iterations < 61000) {
++iterations;
disk_cache::SimpleIndex index(/* io_thread = */ nullptr,
/* cleanup_tracker = */ nullptr, &delegate,
net::DISK_CACHE,
/* simple_index_file = */ nullptr);
// Make sure large enough to not evict on insertion.
index.SetMaxSize(kEntries * 2);
for (int i = 0; i < kEntries; ++i) {
index.InsertEntryForTesting(
i, disk_cache::EntryMetadata(start + base::TimeDelta::FromSeconds(i),
1u));
}
// Trigger an eviction.
base::ElapsedTimer timer;
index.SetMaxSize(kEntries);
index.UpdateEntrySize(0, 1u);
evict_elapsed_ms += timer.Elapsed().InMillisecondsF();
}
LOG(ERROR) << "Average time to evict:" << (evict_elapsed_ms / iterations)
<< "ms";
}
} // namespace