• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2017 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/json/json_reader.h"
6 #include "base/json/json_writer.h"
7 #include "base/memory/ptr_util.h"
8 #include "base/time/time.h"
9 #include "base/values.h"
10 #include "testing/gtest/include/gtest/gtest.h"
11 #include "testing/perf/perf_test.h"
12 
13 namespace base {
14 
15 namespace {
16 // Generates a simple dictionary value with simple data types, a string and a
17 // list.
GenerateDict()18 std::unique_ptr<DictionaryValue> GenerateDict() {
19   auto root = std::make_unique<DictionaryValue>();
20   root->SetDouble("Double", 3.141);
21   root->SetBoolean("Bool", true);
22   root->SetInteger("Int", 42);
23   root->SetString("String", "Foo");
24 
25   auto list = std::make_unique<ListValue>();
26   list->Set(0, std::make_unique<Value>(2.718));
27   list->Set(1, std::make_unique<Value>(false));
28   list->Set(2, std::make_unique<Value>(123));
29   list->Set(3, std::make_unique<Value>("Bar"));
30   root->Set("List", std::move(list));
31 
32   return root;
33 }
34 
35 // Generates a tree-like dictionary value with a size of O(breadth ** depth).
GenerateLayeredDict(int breadth,int depth)36 std::unique_ptr<DictionaryValue> GenerateLayeredDict(int breadth, int depth) {
37   if (depth == 1)
38     return GenerateDict();
39 
40   auto root = GenerateDict();
41   auto next = GenerateLayeredDict(breadth, depth - 1);
42 
43   for (int i = 0; i < breadth; ++i) {
44     root->Set("Dict" + std::to_string(i), next->CreateDeepCopy());
45   }
46 
47   return root;
48 }
49 
50 }  // namespace
51 
52 class JSONPerfTest : public testing::Test {
53  public:
TestWriteAndRead(int breadth,int depth)54   void TestWriteAndRead(int breadth, int depth) {
55     std::string description = "Breadth: " + std::to_string(breadth) +
56                               ", Depth: " + std::to_string(depth);
57     auto dict = GenerateLayeredDict(breadth, depth);
58     std::string json;
59 
60     TimeTicks start_write = TimeTicks::Now();
61     JSONWriter::Write(*dict, &json);
62     TimeTicks end_write = TimeTicks::Now();
63     perf_test::PrintResult("Write", "", description,
64                            (end_write - start_write).InMillisecondsF(), "ms",
65                            true);
66 
67     TimeTicks start_read = TimeTicks::Now();
68     JSONReader::Read(json);
69     TimeTicks end_read = TimeTicks::Now();
70     perf_test::PrintResult("Read", "", description,
71                            (end_read - start_read).InMillisecondsF(), "ms",
72                            true);
73   }
74 };
75 
TEST_F(JSONPerfTest,StressTest)76 TEST_F(JSONPerfTest, StressTest) {
77   for (int i = 0; i < 4; ++i) {
78     for (int j = 0; j < 12; ++j) {
79       TestWriteAndRead(i + 1, j + 1);
80     }
81   }
82 }
83 
84 }  // namespace base
85