xref: /aosp_15_r20/external/cronet/base/timer/lap_timer_unittest.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2019 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.
4 
5 #include "base/timer/lap_timer.h"
6 
7 #include "base/test/task_environment.h"
8 #include "base/time/time.h"
9 #include "build/build_config.h"
10 #include "testing/gtest/include/gtest/gtest.h"
11 
12 // This file contains a minimal unit test for LapTimer, used for benchmarking.
13 // This file is supposed to match closely with the example code, documented in
14 // lap_timer.h. Please update that documentation if you need to change things.
15 
16 namespace base {
17 
18 namespace test {
19 
20 namespace {
21 
22 constexpr base::TimeDelta kTimeLimit = base::Milliseconds(15);
23 constexpr base::TimeDelta kTimeAdvance = base::Milliseconds(1);
24 constexpr int kWarmupRuns = 5;
25 constexpr int kTimeCheckInterval = 10;
26 
27 }  // namespace
28 
TEST(LapTimer,UsageExample)29 TEST(LapTimer, UsageExample) {
30   TaskEnvironment task_environment(TaskEnvironment::TimeSource::MOCK_TIME);
31 
32   LapTimer timer(kWarmupRuns, kTimeLimit, kTimeCheckInterval);
33 
34   EXPECT_FALSE(timer.HasTimeLimitExpired());
35   EXPECT_FALSE(timer.IsWarmedUp());
36 
37   do {
38     task_environment.FastForwardBy(kTimeAdvance);
39     timer.NextLap();
40   } while (!timer.HasTimeLimitExpired());
41 
42   EXPECT_NEAR(timer.LapsPerSecond(), 1000, 0.1);
43   EXPECT_NEAR(timer.TimePerLap().InMillisecondsF(), 1.0f, 0.1);
44   // Output number of laps is 20, because the warm up runs are ignored and the
45   // timer is only checked every kTimeInterval laps.
46   EXPECT_EQ(timer.NumLaps(), 20);
47 
48   EXPECT_TRUE(timer.HasTimeLimitExpired());
49   EXPECT_TRUE(timer.IsWarmedUp());
50 }
51 
52 #if !BUILDFLAG(IS_IOS)
53 // iOS simulator does not support using ThreadTicks.
TEST(LapTimer,ThreadTicksUsageExample)54 TEST(LapTimer, ThreadTicksUsageExample) {
55   TaskEnvironment task_environment(TaskEnvironment::TimeSource::MOCK_TIME);
56   LapTimer timer(kWarmupRuns, kTimeLimit, kTimeCheckInterval,
57                  LapTimer::TimerMethod::kUseThreadTicks);
58 
59   EXPECT_FALSE(timer.HasTimeLimitExpired());
60   EXPECT_FALSE(timer.IsWarmedUp());
61 
62   do {
63     task_environment.FastForwardBy(kTimeAdvance);
64     timer.NextLap();
65   } while (!timer.HasTimeLimitExpired());
66 
67   // Because advancing the TaskEnvironment time won't affect the
68   // ThreadTicks, laps will be much faster than the regular UsageExample.
69   EXPECT_GT(timer.LapsPerSecond(), 1000);
70   EXPECT_LT(timer.TimePerLap().InMillisecondsF(), 1.0f);
71   EXPECT_GT(timer.NumLaps(), 20);
72 
73   EXPECT_TRUE(timer.HasTimeLimitExpired());
74   EXPECT_TRUE(timer.IsWarmedUp());
75 }
76 #endif
77 
78 }  // namespace test
79 }  // namespace base
80