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.
9 #include "base/threading/platform_thread.h"
10 #include "base/time/time.h"
11 #include "testing/gtest/include/gtest/gtest.h"
14 using base::TimeDelta
;
15 using base::TimeTicks
;
19 class MockTimeTicks
: public TimeTicks
{
21 static DWORD
Ticker() {
22 return static_cast<int>(InterlockedIncrement(&ticker_
));
25 static void InstallTicker() {
26 old_tick_function_
= SetMockTickFunction(&Ticker
);
30 static void UninstallTicker() {
31 SetMockTickFunction(old_tick_function_
);
35 static volatile LONG ticker_
;
36 static TickFunctionType old_tick_function_
;
39 volatile LONG
MockTimeTicks::ticker_
;
40 MockTimeTicks::TickFunctionType
MockTimeTicks::old_tick_function_
;
42 HANDLE g_rollover_test_start
;
44 unsigned __stdcall
RolloverTestThreadMain(void* param
) {
45 int64 counter
= reinterpret_cast<int64
>(param
);
46 DWORD rv
= WaitForSingleObject(g_rollover_test_start
, INFINITE
);
47 EXPECT_EQ(rv
, WAIT_OBJECT_0
);
49 TimeTicks last
= TimeTicks::Now();
50 for (int index
= 0; index
< counter
; index
++) {
51 TimeTicks now
= TimeTicks::Now();
52 int64 milliseconds
= (now
- last
).InMilliseconds();
53 // This is a tight loop; we could have looped faster than our
54 // measurements, so the time might be 0 millis.
55 EXPECT_GE(milliseconds
, 0);
56 EXPECT_LT(milliseconds
, 250);
64 TEST(TimeTicks
, WinRollover
) {
65 // The internal counter rolls over at ~49days. We'll use a mock
66 // timer to test this case.
67 // Basic test algorithm:
68 // 1) Set clock to rollover - N
69 // 2) Create N threads
70 // 3) Start the threads
71 // 4) Each thread loops through TimeTicks() N times
72 // 5) Each thread verifies integrity of result.
74 const int kThreads
= 8;
75 // Use int64 so we can cast into a void* without a compiler warning.
76 const int64 kChecks
= 10;
78 // It takes a lot of iterations to reproduce the bug!
80 for (int loop
= 0; loop
< 4096; loop
++) {
82 MockTimeTicks::InstallTicker();
83 g_rollover_test_start
= CreateEvent(0, TRUE
, FALSE
, 0);
84 HANDLE threads
[kThreads
];
86 for (int index
= 0; index
< kThreads
; index
++) {
87 void* argument
= reinterpret_cast<void*>(kChecks
);
89 threads
[index
] = reinterpret_cast<HANDLE
>(
90 _beginthreadex(NULL
, 0, RolloverTestThreadMain
, argument
, 0,
92 EXPECT_NE((HANDLE
)NULL
, threads
[index
]);
96 SetEvent(g_rollover_test_start
);
98 // Wait for threads to finish
99 for (int index
= 0; index
< kThreads
; index
++) {
100 DWORD rv
= WaitForSingleObject(threads
[index
], INFINITE
);
101 EXPECT_EQ(rv
, WAIT_OBJECT_0
);
102 // Since using _beginthreadex() (as opposed to _beginthread),
103 // an explicit CloseHandle() is supposed to be called.
104 CloseHandle(threads
[index
]);
107 CloseHandle(g_rollover_test_start
);
110 MockTimeTicks::UninstallTicker();
114 TEST(TimeTicks
, SubMillisecondTimers
) {
115 // HighResNow doesn't work on some systems. Since the product still works
116 // even if it doesn't work, it makes this entire test questionable.
117 if (!TimeTicks::IsHighResClockWorking())
120 const int kRetries
= 1000;
121 bool saw_submillisecond_timer
= false;
123 // Run kRetries attempts to see a sub-millisecond timer.
124 for (int index
= 0; index
< kRetries
; index
++) {
125 TimeTicks last_time
= TimeTicks::HighResNow();
127 // Spin until the clock has detected a change.
129 delta
= TimeTicks::HighResNow() - last_time
;
130 } while (delta
.InMicroseconds() == 0);
131 if (delta
.InMicroseconds() < 1000) {
132 saw_submillisecond_timer
= true;
136 EXPECT_TRUE(saw_submillisecond_timer
);
139 TEST(TimeTicks
, TimeGetTimeCaps
) {
140 // Test some basic assumptions that we expect about how timeGetDevCaps works.
143 MMRESULT status
= timeGetDevCaps(&caps
, sizeof(caps
));
144 EXPECT_EQ(TIMERR_NOERROR
, status
);
145 if (status
!= TIMERR_NOERROR
) {
146 printf("Could not get timeGetDevCaps\n");
150 EXPECT_GE(static_cast<int>(caps
.wPeriodMin
), 1);
151 EXPECT_GT(static_cast<int>(caps
.wPeriodMax
), 1);
152 EXPECT_GE(static_cast<int>(caps
.wPeriodMin
), 1);
153 EXPECT_GT(static_cast<int>(caps
.wPeriodMax
), 1);
154 printf("timeGetTime range is %d to %dms\n", caps
.wPeriodMin
,
158 TEST(TimeTicks
, QueryPerformanceFrequency
) {
159 // Test some basic assumptions that we expect about QPC.
161 LARGE_INTEGER frequency
;
162 BOOL rv
= QueryPerformanceFrequency(&frequency
);
164 EXPECT_GT(frequency
.QuadPart
, 1000000); // Expect at least 1MHz
165 printf("QueryPerformanceFrequency is %5.2fMHz\n",
166 frequency
.QuadPart
/ 1000000.0);
169 TEST(TimeTicks
, TimerPerformance
) {
170 // Verify that various timer mechanisms can always complete quickly.
171 // Note: This is a somewhat arbitrary test.
172 const int kLoops
= 10000;
174 typedef TimeTicks (*TestFunc
)();
177 const char *description
;
179 // Cheating a bit here: assumes sizeof(TimeTicks) == sizeof(Time)
180 // in order to create a single test case list.
181 COMPILE_ASSERT(sizeof(TimeTicks
) == sizeof(Time
),
182 test_only_works_with_same_sizes
);
184 { reinterpret_cast<TestFunc
>(Time::Now
), "Time::Now" },
185 { TimeTicks::Now
, "TimeTicks::Now" },
186 { TimeTicks::HighResNow
, "TimeTicks::HighResNow" },
191 while (cases
[test_case
].func
) {
192 TimeTicks start
= TimeTicks::HighResNow();
193 for (int index
= 0; index
< kLoops
; index
++)
194 cases
[test_case
].func();
195 TimeTicks stop
= TimeTicks::HighResNow();
196 // Turning off the check for acceptible delays. Without this check,
197 // the test really doesn't do much other than measure. But the
198 // measurements are still useful for testing timers on various platforms.
199 // The reason to remove the check is because the tests run on many
200 // buildbots, some of which are VMs. These machines can run horribly
201 // slow, and there is really no value for checking against a max timer.
202 //const int kMaxTime = 35; // Maximum acceptible milliseconds for test.
203 //EXPECT_LT((stop - start).InMilliseconds(), kMaxTime);
204 printf("%s: %1.2fus per call\n", cases
[test_case
].description
,
205 (stop
- start
).InMillisecondsF() * 1000 / kLoops
);
210 // http://crbug.com/396384
211 TEST(TimeTicks
, DISABLED_Drift
) {
212 // If QPC is disabled, this isn't measuring anything.
213 if (!TimeTicks::IsHighResClockWorking())
216 const int kIterations
= 100;
217 int64 total_drift
= 0;
219 for (int i
= 0; i
< kIterations
; ++i
) {
220 int64 drift_microseconds
= TimeTicks::GetQPCDriftMicroseconds();
222 // Make sure the drift never exceeds our limit.
223 EXPECT_LT(drift_microseconds
, 50000);
225 // Sleep for a few milliseconds (note that it means 1000 microseconds).
226 // If we check the drift too frequently, it's going to increase
227 // monotonically, making our measurement less realistic.
228 base::PlatformThread::Sleep(
229 base::TimeDelta::FromMilliseconds((i
% 2 == 0) ? 1 : 2));
231 total_drift
+= drift_microseconds
;
234 // Sanity check. We expect some time drift to occur, especially across
235 // the number of iterations we do.
236 EXPECT_LT(0, total_drift
);
238 printf("average time drift in microseconds: %lld\n",
239 total_drift
/ kIterations
);
242 int64
QPCValueToMicrosecondsSafely(LONGLONG qpc_value
,
243 int64 ticks_per_second
) {
244 int64 whole_seconds
= qpc_value
/ ticks_per_second
;
245 int64 leftover_ticks
= qpc_value
% ticks_per_second
;
246 int64 microseconds
= (whole_seconds
* Time::kMicrosecondsPerSecond
) +
247 ((leftover_ticks
* Time::kMicrosecondsPerSecond
) /
252 TEST(TimeTicks
, FromQPCValue
) {
253 if (!TimeTicks::IsHighResClockWorking())
255 LARGE_INTEGER frequency
;
256 QueryPerformanceFrequency(&frequency
);
257 int64 ticks_per_second
= frequency
.QuadPart
;
258 LONGLONG qpc_value
= Time::kQPCOverflowThreshold
;
259 TimeTicks expected_value
= TimeTicks::FromInternalValue(
260 QPCValueToMicrosecondsSafely(qpc_value
+ 1, ticks_per_second
));
261 EXPECT_EQ(expected_value
,
262 TimeTicks::FromQPCValue(qpc_value
+ 1));
263 expected_value
= TimeTicks::FromInternalValue(
264 QPCValueToMicrosecondsSafely(qpc_value
, ticks_per_second
));
265 EXPECT_EQ(expected_value
,
266 TimeTicks::FromQPCValue(qpc_value
));
267 expected_value
= TimeTicks::FromInternalValue(
268 QPCValueToMicrosecondsSafely(qpc_value
- 1, ticks_per_second
));
269 EXPECT_EQ(expected_value
,
270 TimeTicks::FromQPCValue(qpc_value
- 1));