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
;
20 using base::TraceTicks
;
24 class MockTimeTicks
: public TimeTicks
{
26 static DWORD
Ticker() {
27 return static_cast<int>(InterlockedIncrement(&ticker_
));
30 static void InstallTicker() {
31 old_tick_function_
= SetMockTickFunction(&Ticker
);
35 static void UninstallTicker() {
36 SetMockTickFunction(old_tick_function_
);
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);
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!
85 for (int loop
= 0; loop
< 4096; loop
++) {
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
);
94 threads
[index
] = reinterpret_cast<HANDLE
>(
95 _beginthreadex(NULL
, 0, RolloverTestThreadMain
, argument
, 0,
97 EXPECT_NE((HANDLE
)NULL
, threads
[index
]);
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
);
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())
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();
132 // Spin until the clock has detected a change.
134 delta
= TimeTicks::Now() - last_time
;
135 } while (delta
.InMicroseconds() == 0);
136 if (delta
.InMicroseconds() < 1000) {
137 saw_submillisecond_timer
= true;
141 EXPECT_TRUE(saw_submillisecond_timer
);
144 TEST(TimeTicks
, TimeGetTimeCaps
) {
145 // Test some basic assumptions that we expect about how timeGetDevCaps works.
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");
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
,
163 TEST(TimeTicks
, QueryPerformanceFrequency
) {
164 // Test some basic assumptions that we expect about QPC.
166 LARGE_INTEGER frequency
;
167 BOOL rv
= QueryPerformanceFrequency(&frequency
);
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
)();
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
);
189 { reinterpret_cast<TestFunc
>(&Time::Now
), "Time::Now" },
190 { &TimeTicks::Now
, "TimeTicks::Now" },
191 { reinterpret_cast<TestFunc
>(&TraceTicks::Now
), "TraceTicks::Now" },
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
);
215 TEST(TimeTicks
, FromQPCValue
) {
216 if (!TimeTicks::IsHighResolution())
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;
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
) /
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
,
265 << "ticks=" << ticks
<< ", to be converted via logic path: "
266 << (ticks
< Time::kQPCOverflowThreshold
? "FAST" : "SAFE");