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