blob: 8b65985380e5b20866651831cc82cdeb4ba590cb [file] [log] [blame]
Benoît Lizé0af836f2019-05-15 09:44:411// 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
5#include "base/timer/elapsed_timer.h"
6
7#include "base/threading/platform_thread.h"
8#include "base/time/time.h"
9#include "testing/gtest/include/gtest/gtest.h"
10
11namespace base {
12
13namespace {
14
15constexpr TimeDelta kSleepDuration = TimeDelta::FromMilliseconds(20);
16
17}
18
19TEST(ElapsedTimerTest, Simple) {
20 ElapsedTimer timer;
21
22 PlatformThread::Sleep(kSleepDuration);
23 EXPECT_GE(timer.Elapsed(), kSleepDuration);
24
25 // Can call |Elapsed()| multiple times.
26 PlatformThread::Sleep(kSleepDuration);
27 EXPECT_GE(timer.Elapsed(), 2 * kSleepDuration);
28}
29
30class ElapsedThreadTimerTest : public ::testing::Test {
31 protected:
32 void SetUp() override {
33 if (ThreadTicks::IsSupported())
34 ThreadTicks::WaitUntilInitialized();
35 }
36};
37
38TEST_F(ElapsedThreadTimerTest, IsSupported) {
39 ElapsedThreadTimer timer;
40 if (!ThreadTicks::IsSupported()) {
41 EXPECT_FALSE(timer.is_supported());
42 EXPECT_EQ(TimeDelta(), timer.Elapsed());
43 } else {
44 EXPECT_TRUE(timer.is_supported());
45 }
46}
47
48TEST_F(ElapsedThreadTimerTest, Simple) {
49 if (!ThreadTicks::IsSupported())
50 return;
51
52 ElapsedThreadTimer timer;
53 EXPECT_TRUE(timer.is_supported());
54
55 // 1ms of work.
56 constexpr TimeDelta kLoopingTime = TimeDelta::FromMilliseconds(1);
57 const ThreadTicks start_ticks = ThreadTicks::Now();
58 while (ThreadTicks::Now() - start_ticks < kLoopingTime) {
59 }
60
61 EXPECT_GE(timer.Elapsed(), kLoopingTime);
62}
63
64TEST_F(ElapsedThreadTimerTest, DoesNotCountSleep) {
65 if (!ThreadTicks::IsSupported())
66 return;
67
68 ElapsedThreadTimer timer;
69 EXPECT_TRUE(timer.is_supported());
70
71 PlatformThread::Sleep(kSleepDuration);
72 // Sleep time is not accounted for.
73 EXPECT_LT(timer.Elapsed(), kSleepDuration);
74}
75
76} // namespace base