1 //===-- TimerTest.cpp -------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "lldb/Utility/StreamString.h"
11 #include "lldb/Utility/Timer.h"
12 #include "gtest/gtest.h"
13 #include <thread>
14 
15 using namespace lldb_private;
16 
17 TEST(TimerTest, CategoryTimes) {
18   Timer::ResetCategoryTimes();
19   {
20     static Timer::Category tcat("CAT1");
21     Timer t(tcat, "");
22     std::this_thread::sleep_for(std::chrono::milliseconds(10));
23   }
24   StreamString ss;
25   Timer::DumpCategoryTimes(&ss);
26   double seconds;
27   ASSERT_EQ(1, sscanf(ss.GetData(), "%lf sec for CAT1", &seconds));
28   EXPECT_LT(0.001, seconds);
29   EXPECT_GT(0.1, seconds);
30 }
31 
32 TEST(TimerTest, CategoryTimesNested) {
33   Timer::ResetCategoryTimes();
34   {
35     static Timer::Category tcat1("CAT1");
36     Timer t1(tcat1, "");
37     std::this_thread::sleep_for(std::chrono::milliseconds(10));
38     // Explicitly testing the same category as above.
39     Timer t2(tcat1, "");
40     std::this_thread::sleep_for(std::chrono::milliseconds(10));
41   }
42   StreamString ss;
43   Timer::DumpCategoryTimes(&ss);
44   double seconds;
45   // It should only appear once.
46   ASSERT_EQ(ss.GetString().count("CAT1"), 1U);
47   ASSERT_EQ(1, sscanf(ss.GetData(), "%lf sec for CAT1", &seconds));
48   EXPECT_LT(0.002, seconds);
49   EXPECT_GT(0.2, seconds);
50 }
51 
52 TEST(TimerTest, CategoryTimes2) {
53   Timer::ResetCategoryTimes();
54   {
55     static Timer::Category tcat1("CAT1");
56     Timer t1(tcat1, "");
57     std::this_thread::sleep_for(std::chrono::milliseconds(100));
58     static Timer::Category tcat2("CAT2");
59     Timer t2(tcat2, "");
60     std::this_thread::sleep_for(std::chrono::milliseconds(10));
61   }
62   StreamString ss;
63   Timer::DumpCategoryTimes(&ss);
64   double seconds1, seconds2;
65   ASSERT_EQ(2, sscanf(ss.GetData(), "%lf sec for CAT1%*[\n ]%lf sec for CAT2",
66                       &seconds1, &seconds2))
67       << "String: " << ss.GetData();
68   EXPECT_LT(0.01, seconds1);
69   EXPECT_GT(1, seconds1);
70   EXPECT_LT(0.001, seconds2);
71   EXPECT_GT(0.1, seconds2);
72 }
73