Yuri Wiitala | eb8eee7 | 2019-03-26 15:52:43 -0700 | [diff] [blame^] | 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 | |
| 5 | #include "platform/api/time.h" |
| 6 | |
| 7 | #include <thread> |
| 8 | |
| 9 | #include "third_party/googletest/src/googletest/include/gtest/gtest.h" |
| 10 | |
| 11 | using std::chrono::microseconds; |
| 12 | using std::chrono::milliseconds; |
| 13 | |
| 14 | namespace openscreen { |
| 15 | namespace platform { |
| 16 | |
| 17 | TEST(TimeTest, PlatformClockIsMonotonic) { |
| 18 | constexpr auto kSleepPeriod = milliseconds(2); |
| 19 | for (int i = 0; i < 50; ++i) { |
| 20 | const auto start = Clock::now(); |
| 21 | std::this_thread::sleep_for(kSleepPeriod); |
| 22 | const auto stop = Clock::now(); |
| 23 | EXPECT_GE(stop - start, kSleepPeriod / 2); |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | TEST(TimeTest, PlatformClockHasSufficientResolution) { |
| 28 | constexpr std::chrono::duration<int, kRequiredClockResolution> kMaxDuration( |
| 29 | 1); |
| 30 | constexpr int kMaxRetries = 100; |
| 31 | |
| 32 | // Loop until a small-enough clock change is observed. The platform is given |
| 33 | // multiple chances because unpredictable events, like thread context |
| 34 | // switches, could suspend the current thread for a "long" time, masking what |
| 35 | // the clock is actually capable of. |
| 36 | Clock::duration delta = microseconds(0); |
| 37 | for (int i = 0; i < kMaxRetries; ++i) { |
| 38 | const auto start = Clock::now(); |
| 39 | // Loop until the clock changes. |
| 40 | do { |
| 41 | delta = Clock::now() - start; |
| 42 | ASSERT_LE(microseconds(0), delta); |
| 43 | } while (delta == microseconds(0)); |
| 44 | |
| 45 | if (delta <= kMaxDuration) { |
| 46 | break; |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | EXPECT_LE(delta, kMaxDuration); |
| 51 | } |
| 52 | |
| 53 | } // namespace platform |
| 54 | } // namespace openscreen |