blob: 9a4f40cbd106cd9fed28300a217462bcce4cc380 [file] [log] [blame]
Yuri Wiitalaeb8eee72019-03-26 15:52:43 -07001// 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 "platform/api/time.h"
6
7#include <thread>
8
Jordan Bayles2d01f172019-06-07 11:11:50 -07009#include "gtest/gtest.h"
Yuri Wiitalaeb8eee72019-03-26 15:52:43 -070010
11using std::chrono::microseconds;
12using std::chrono::milliseconds;
13
14namespace openscreen {
15namespace platform {
Yuri Wiitalaf162a612019-11-22 22:46:04 -080016namespace {
Yuri Wiitalaeb8eee72019-03-26 15:52:43 -070017
Yuri Wiitalaf162a612019-11-22 22:46:04 -080018// Tests that the clock always seems to tick forward. If this test is broken, or
19// is flaky, the time source is probably not monotonic.
Yuri Wiitalaeb8eee72019-03-26 15:52:43 -070020TEST(TimeTest, PlatformClockIsMonotonic) {
21 constexpr auto kSleepPeriod = milliseconds(2);
22 for (int i = 0; i < 50; ++i) {
23 const auto start = Clock::now();
24 std::this_thread::sleep_for(kSleepPeriod);
25 const auto stop = Clock::now();
26 EXPECT_GE(stop - start, kSleepPeriod / 2);
27 }
28}
29
Yuri Wiitalaf162a612019-11-22 22:46:04 -080030// Tests that the clock ticks at least 10000 times per second, a requirement
31// specified in the API header comments.
Yuri Wiitalaeb8eee72019-03-26 15:52:43 -070032TEST(TimeTest, PlatformClockHasSufficientResolution) {
Yuri Wiitalaf162a612019-11-22 22:46:04 -080033 constexpr std::chrono::duration<int, Clock::kRequiredResolution>
34 kMaxAllowedDurationBetweenTicks(1);
Yuri Wiitalaeb8eee72019-03-26 15:52:43 -070035 constexpr int kMaxRetries = 100;
36
37 // Loop until a small-enough clock change is observed. The platform is given
38 // multiple chances because unpredictable events, like thread context
39 // switches, could suspend the current thread for a "long" time, masking what
40 // the clock is actually capable of.
41 Clock::duration delta = microseconds(0);
42 for (int i = 0; i < kMaxRetries; ++i) {
43 const auto start = Clock::now();
44 // Loop until the clock changes.
45 do {
46 delta = Clock::now() - start;
47 ASSERT_LE(microseconds(0), delta);
48 } while (delta == microseconds(0));
49
Yuri Wiitalaf162a612019-11-22 22:46:04 -080050 if (delta <= kMaxAllowedDurationBetweenTicks) {
Yuri Wiitalaeb8eee72019-03-26 15:52:43 -070051 break;
52 }
53 }
54
Yuri Wiitalaf162a612019-11-22 22:46:04 -080055 EXPECT_LE(delta, kMaxAllowedDurationBetweenTicks);
Yuri Wiitalaeb8eee72019-03-26 15:52:43 -070056}
57
Yuri Wiitalaf162a612019-11-22 22:46:04 -080058} // namespace
Yuri Wiitalaeb8eee72019-03-26 15:52:43 -070059} // namespace platform
60} // namespace openscreen