Remove linux_chromium_gn_dbg from the chromium CQ.
[chromium-blink-merge.git] / base / time / time_win_unittest.cc
blob75b237ed65da1a36f9f17c9da6ce0352113ac504
1 // Copyright (c) 2012 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.
5 #include <windows.h>
6 #include <mmsystem.h>
7 #include <process.h>
9 #include <cmath>
10 #include <limits>
11 #include <vector>
13 #include "base/threading/platform_thread.h"
14 #include "base/time/time.h"
15 #include "testing/gtest/include/gtest/gtest.h"
17 using base::Time;
18 using base::TimeDelta;
19 using base::TimeTicks;
20 using base::TraceTicks;
22 namespace {
24 class MockTimeTicks : public TimeTicks {
25 public:
26 static DWORD Ticker() {
27 return static_cast<int>(InterlockedIncrement(&ticker_));
30 static void InstallTicker() {
31 old_tick_function_ = SetMockTickFunction(&Ticker);
32 ticker_ = -5;
35 static void UninstallTicker() {
36 SetMockTickFunction(old_tick_function_);
39 private:
40 static volatile LONG ticker_;
41 static TickFunctionType old_tick_function_;
44 volatile LONG MockTimeTicks::ticker_;
45 MockTimeTicks::TickFunctionType MockTimeTicks::old_tick_function_;
47 HANDLE g_rollover_test_start;
49 unsigned __stdcall RolloverTestThreadMain(void* param) {
50 int64 counter = reinterpret_cast<int64>(param);
51 DWORD rv = WaitForSingleObject(g_rollover_test_start, INFINITE);
52 EXPECT_EQ(rv, WAIT_OBJECT_0);
54 TimeTicks last = TimeTicks::Now();
55 for (int index = 0; index < counter; index++) {
56 TimeTicks now = TimeTicks::Now();
57 int64 milliseconds = (now - last).InMilliseconds();
58 // This is a tight loop; we could have looped faster than our
59 // measurements, so the time might be 0 millis.
60 EXPECT_GE(milliseconds, 0);
61 EXPECT_LT(milliseconds, 250);
62 last = now;
64 return 0;
67 } // namespace
69 TEST(TimeTicks, WinRollover) {
70 // The internal counter rolls over at ~49days. We'll use a mock
71 // timer to test this case.
72 // Basic test algorithm:
73 // 1) Set clock to rollover - N
74 // 2) Create N threads
75 // 3) Start the threads
76 // 4) Each thread loops through TimeTicks() N times
77 // 5) Each thread verifies integrity of result.
79 const int kThreads = 8;
80 // Use int64 so we can cast into a void* without a compiler warning.
81 const int64 kChecks = 10;
83 // It takes a lot of iterations to reproduce the bug!
84 // (See bug 1081395)
85 for (int loop = 0; loop < 4096; loop++) {
86 // Setup
87 MockTimeTicks::InstallTicker();
88 g_rollover_test_start = CreateEvent(0, TRUE, FALSE, 0);
89 HANDLE threads[kThreads];
91 for (int index = 0; index < kThreads; index++) {
92 void* argument = reinterpret_cast<void*>(kChecks);
93 unsigned thread_id;
94 threads[index] = reinterpret_cast<HANDLE>(
95 _beginthreadex(NULL, 0, RolloverTestThreadMain, argument, 0,
96 &thread_id));
97 EXPECT_NE((HANDLE)NULL, threads[index]);
100 // Start!
101 SetEvent(g_rollover_test_start);
103 // Wait for threads to finish
104 for (int index = 0; index < kThreads; index++) {
105 DWORD rv = WaitForSingleObject(threads[index], INFINITE);
106 EXPECT_EQ(rv, WAIT_OBJECT_0);
107 // Since using _beginthreadex() (as opposed to _beginthread),
108 // an explicit CloseHandle() is supposed to be called.
109 CloseHandle(threads[index]);
112 CloseHandle(g_rollover_test_start);
114 // Teardown
115 MockTimeTicks::UninstallTicker();
119 TEST(TimeTicks, SubMillisecondTimers) {
120 // IsHighResolution() is false on some systems. Since the product still works
121 // even if it's false, it makes this entire test questionable.
122 if (!TimeTicks::IsHighResolution())
123 return;
125 const int kRetries = 1000;
126 bool saw_submillisecond_timer = false;
128 // Run kRetries attempts to see a sub-millisecond timer.
129 for (int index = 0; index < kRetries; index++) {
130 TimeTicks last_time = TimeTicks::Now();
131 TimeDelta delta;
132 // Spin until the clock has detected a change.
133 do {
134 delta = TimeTicks::Now() - last_time;
135 } while (delta.InMicroseconds() == 0);
136 if (delta.InMicroseconds() < 1000) {
137 saw_submillisecond_timer = true;
138 break;
141 EXPECT_TRUE(saw_submillisecond_timer);
144 TEST(TimeTicks, TimeGetTimeCaps) {
145 // Test some basic assumptions that we expect about how timeGetDevCaps works.
147 TIMECAPS caps;
148 MMRESULT status = timeGetDevCaps(&caps, sizeof(caps));
149 EXPECT_EQ(TIMERR_NOERROR, status);
150 if (status != TIMERR_NOERROR) {
151 printf("Could not get timeGetDevCaps\n");
152 return;
155 EXPECT_GE(static_cast<int>(caps.wPeriodMin), 1);
156 EXPECT_GT(static_cast<int>(caps.wPeriodMax), 1);
157 EXPECT_GE(static_cast<int>(caps.wPeriodMin), 1);
158 EXPECT_GT(static_cast<int>(caps.wPeriodMax), 1);
159 printf("timeGetTime range is %d to %dms\n", caps.wPeriodMin,
160 caps.wPeriodMax);
163 TEST(TimeTicks, QueryPerformanceFrequency) {
164 // Test some basic assumptions that we expect about QPC.
166 LARGE_INTEGER frequency;
167 BOOL rv = QueryPerformanceFrequency(&frequency);
168 EXPECT_EQ(TRUE, rv);
169 EXPECT_GT(frequency.QuadPart, 1000000); // Expect at least 1MHz
170 printf("QueryPerformanceFrequency is %5.2fMHz\n",
171 frequency.QuadPart / 1000000.0);
174 TEST(TimeTicks, TimerPerformance) {
175 // Verify that various timer mechanisms can always complete quickly.
176 // Note: This is a somewhat arbitrary test.
177 const int kLoops = 10000;
179 typedef TimeTicks (*TestFunc)();
180 struct TestCase {
181 TestFunc func;
182 const char *description;
184 // Cheating a bit here: assumes sizeof(TimeTicks) == sizeof(Time)
185 // in order to create a single test case list.
186 COMPILE_ASSERT(sizeof(TimeTicks) == sizeof(Time),
187 test_only_works_with_same_sizes);
188 TestCase cases[] = {
189 { reinterpret_cast<TestFunc>(&Time::Now), "Time::Now" },
190 { &TimeTicks::Now, "TimeTicks::Now" },
191 { reinterpret_cast<TestFunc>(&TraceTicks::Now), "TraceTicks::Now" },
192 { NULL, "" }
195 int test_case = 0;
196 while (cases[test_case].func) {
197 TimeTicks start = TimeTicks::Now();
198 for (int index = 0; index < kLoops; index++)
199 cases[test_case].func();
200 TimeTicks stop = TimeTicks::Now();
201 // Turning off the check for acceptible delays. Without this check,
202 // the test really doesn't do much other than measure. But the
203 // measurements are still useful for testing timers on various platforms.
204 // The reason to remove the check is because the tests run on many
205 // buildbots, some of which are VMs. These machines can run horribly
206 // slow, and there is really no value for checking against a max timer.
207 //const int kMaxTime = 35; // Maximum acceptible milliseconds for test.
208 //EXPECT_LT((stop - start).InMilliseconds(), kMaxTime);
209 printf("%s: %1.2fus per call\n", cases[test_case].description,
210 (stop - start).InMillisecondsF() * 1000 / kLoops);
211 test_case++;
215 TEST(TimeTicks, FromQPCValue) {
216 if (!TimeTicks::IsHighResolution())
217 return;
219 LARGE_INTEGER frequency;
220 ASSERT_TRUE(QueryPerformanceFrequency(&frequency));
221 const int64 ticks_per_second = frequency.QuadPart;
222 ASSERT_GT(ticks_per_second, 0);
224 // Generate the tick values to convert, advancing the tick count by varying
225 // amounts. These values will ensure that both the fast and overflow-safe
226 // conversion logic in FromQPCValue() is tested, and across the entire range
227 // of possible QPC tick values.
228 std::vector<int64> test_cases;
229 test_cases.push_back(0);
230 const int kNumAdvancements = 100;
231 int64 ticks = 0;
232 int64 ticks_increment = 10;
233 for (int i = 0; i < kNumAdvancements; ++i) {
234 test_cases.push_back(ticks);
235 ticks += ticks_increment;
236 ticks_increment = ticks_increment * 6 / 5;
238 test_cases.push_back(Time::kQPCOverflowThreshold - 1);
239 test_cases.push_back(Time::kQPCOverflowThreshold);
240 test_cases.push_back(Time::kQPCOverflowThreshold + 1);
241 ticks = Time::kQPCOverflowThreshold + 10;
242 ticks_increment = 10;
243 for (int i = 0; i < kNumAdvancements; ++i) {
244 test_cases.push_back(ticks);
245 ticks += ticks_increment;
246 ticks_increment = ticks_increment * 6 / 5;
248 test_cases.push_back(std::numeric_limits<int64>::max());
250 // Test that the conversions using FromQPCValue() match those computed here
251 // using simple floating-point arithmetic. The floating-point math provides
252 // enough precision to confirm the implementation is correct to the
253 // microsecond for all |test_cases| (though it would be insufficient to
254 // confirm many "very large" tick values which are not being tested here).
255 for (int64 ticks : test_cases) {
256 const double expected_microseconds_since_origin =
257 (static_cast<double>(ticks) * Time::kMicrosecondsPerSecond) /
258 ticks_per_second;
259 const TimeTicks converted_value = TimeTicks::FromQPCValue(ticks);
260 const double converted_microseconds_since_origin =
261 static_cast<double>((converted_value - TimeTicks()).InMicroseconds());
262 EXPECT_NEAR(expected_microseconds_since_origin,
263 converted_microseconds_since_origin,
264 1.0)
265 << "ticks=" << ticks << ", to be converted via logic path: "
266 << (ticks < Time::kQPCOverflowThreshold ? "FAST" : "SAFE");