1 // Copyright 2017 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/json/json_reader.h"
6 #include "base/json/json_writer.h"
7 #include "base/memory/ptr_util.h"
8 #include "base/strings/string_number_conversions.h"
9 #include "base/time/time.h"
10 #include "base/values.h"
11 #include "build/build_config.h"
12 #include "testing/gtest/include/gtest/gtest.h"
13 #include "testing/perf/perf_result_reporter.h"
19 constexpr char kMetricPrefixJSON[] = "JSON.";
20 constexpr char kMetricReadTime[] = "read_time";
21 constexpr char kMetricWriteTime[] = "write_time";
23 perf_test::PerfResultReporter SetUpReporter(const std::string& story_name) {
24 perf_test::PerfResultReporter reporter(kMetricPrefixJSON, story_name);
25 reporter.RegisterImportantMetric(kMetricReadTime, "ms");
26 reporter.RegisterImportantMetric(kMetricWriteTime, "ms");
30 // Generates a simple dictionary value with simple data types, a string and a
32 Value::Dict GenerateDict() {
34 root.Set("Double", 3.141);
35 root.Set("Bool", true);
37 root.Set("String", "Foo");
44 root.Set("List", std::move(list));
49 // Generates a tree-like dictionary value with a size of O(breadth ** depth).
50 Value::Dict GenerateLayeredDict(int breadth, int depth) {
52 return GenerateDict();
54 Value::Dict root = GenerateDict();
55 Value::Dict next = GenerateLayeredDict(breadth, depth - 1);
57 for (int i = 0; i < breadth; ++i) {
58 root.Set("Dict" + base::NumberToString(i), next.Clone());
66 class JSONPerfTest : public testing::Test {
68 void TestWriteAndRead(int breadth, int depth) {
69 std::string description = "Breadth: " + base::NumberToString(breadth) +
70 ", Depth: " + base::NumberToString(depth);
71 Value::Dict dict = GenerateLayeredDict(breadth, depth);
74 TimeTicks start_write = TimeTicks::Now();
75 JSONWriter::Write(dict, &json);
76 TimeTicks end_write = TimeTicks::Now();
77 auto reporter = SetUpReporter("breadth_" + base::NumberToString(breadth) +
78 "_depth_" + base::NumberToString(depth));
79 reporter.AddResult(kMetricWriteTime, end_write - start_write);
81 TimeTicks start_read = TimeTicks::Now();
82 JSONReader::Read(json);
83 TimeTicks end_read = TimeTicks::Now();
84 reporter.AddResult(kMetricReadTime, end_read - start_read);
88 TEST_F(JSONPerfTest, StressTest) {
89 // These loop ranges are chosen such that this test will complete in a
90 // reasonable amount of time and will work on a 32-bit build without hitting
91 // an out-of-memory failure. Having j go to 10 uses over 2 GiB of memory and
92 // might hit Android timeouts so be wary of going that high.
93 for (int i = 0; i < 4; ++i) {
94 for (int j = 0; j < 10; ++j) {
95 TestWriteAndRead(i + 1, j + 1);