lap_timer_unittest.cc 2.5 KB

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