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.
6 // Windows Timer Primer
8 // A good article: http://www.ddj.com/windows/184416651
9 // A good mozilla bug: http://bugzilla.mozilla.org/show_bug.cgi?id=363258
11 // The default windows timer, GetSystemTimeAsFileTime is not very precise.
12 // It is only good to ~15.5ms.
14 // QueryPerformanceCounter is the logical choice for a high-precision timer.
15 // However, it is known to be buggy on some hardware. Specifically, it can
16 // sometimes "jump". On laptops, QPC can also be very expensive to call.
17 // It's 3-4x slower than timeGetTime() on desktops, but can be 10x slower
18 // on laptops. A unittest exists which will show the relative cost of various
19 // timers on any system.
21 // The next logical choice is timeGetTime(). timeGetTime has a precision of
22 // 1ms, but only if you call APIs (timeBeginPeriod()) which affect all other
23 // applications on the system. By default, precision is only 15.5ms.
24 // Unfortunately, we don't want to call timeBeginPeriod because we don't
25 // want to affect other applications. Further, on mobile platforms, use of
26 // faster multimedia timers can hurt battery life. See the intel
27 // article about this here:
28 // http://softwarecommunity.intel.com/articles/eng/1086.htm
30 // To work around all this, we're going to generally use timeGetTime(). We
31 // will only increase the system-wide timer if we're not running on battery
32 // power. Using timeBeginPeriod(1) is a requirement in order to make our
33 // message loop waits have the same resolution that our time measurements
34 // do. Otherwise, WaitForSingleObject(..., 1) will no less than 15ms when
35 // there is nothing else to waken the Wait.
37 #include "base/time.h"
39 #pragma comment(lib, "winmm.lib")
43 #include "base/basictypes.h"
44 #include "base/logging.h"
46 #include "base/memory/singleton.h"
47 #include "base/synchronization/lock.h"
50 using base::TimeDelta
;
51 using base::TimeTicks
;
55 // From MSDN, FILETIME "Contains a 64-bit value representing the number of
56 // 100-nanosecond intervals since January 1, 1601 (UTC)."
57 int64
FileTimeToMicroseconds(const FILETIME
& ft
) {
58 // Need to bit_cast to fix alignment, then divide by 10 to convert
59 // 100-nanoseconds to milliseconds. This only works on little-endian
61 return bit_cast
<int64
, FILETIME
>(ft
) / 10;
64 void MicrosecondsToFileTime(int64 us
, FILETIME
* ft
) {
65 DCHECK_GE(us
, 0LL) << "Time is less than 0, negative values are not "
66 "representable in FILETIME";
68 // Multiply by 10 to convert milliseconds to 100-nanoseconds. Bit_cast will
69 // handle alignment problems. This only works on little-endian machines.
70 *ft
= bit_cast
<FILETIME
, int64
>(us
* 10);
73 int64
CurrentWallclockMicroseconds() {
75 ::GetSystemTimeAsFileTime(&ft
);
76 return FileTimeToMicroseconds(ft
);
79 // Time between resampling the un-granular clock for this API. 60 seconds.
80 const int kMaxMillisecondsToAvoidDrift
= 60 * Time::kMillisecondsPerSecond
;
82 int64 initial_time
= 0;
83 TimeTicks initial_ticks
;
85 void InitializeClock() {
86 initial_ticks
= TimeTicks::Now();
87 initial_time
= CurrentWallclockMicroseconds();
92 // Time -----------------------------------------------------------------------
94 // The internal representation of Time uses FILETIME, whose epoch is 1601-01-01
95 // 00:00:00 UTC. ((1970-1601)*365+89)*24*60*60*1000*1000, where 89 is the
96 // number of leap year days between 1601 and 1970: (1970-1601)/4 excluding
97 // 1700, 1800, and 1900.
99 const int64
Time::kTimeTToMicrosecondsOffset
= GG_INT64_C(11644473600000000);
101 bool Time::high_resolution_timer_enabled_
= false;
102 int Time::high_resolution_timer_activated_
= 0;
106 if (initial_time
== 0)
109 // We implement time using the high-resolution timers so that we can get
110 // timeouts which are smaller than 10-15ms. If we just used
111 // CurrentWallclockMicroseconds(), we'd have the less-granular timer.
113 // To make this work, we initialize the clock (initial_time) and the
114 // counter (initial_ctr). To compute the initial time, we can check
115 // the number of ticks that have elapsed, and compute the delta.
117 // To avoid any drift, we periodically resync the counters to the system
120 TimeTicks ticks
= TimeTicks::Now();
122 // Calculate the time elapsed since we started our timer
123 TimeDelta elapsed
= ticks
- initial_ticks
;
125 // Check if enough time has elapsed that we need to resync the clock.
126 if (elapsed
.InMilliseconds() > kMaxMillisecondsToAvoidDrift
) {
131 return Time(elapsed
+ Time(initial_time
));
136 Time
Time::NowFromSystemTime() {
139 return Time(initial_time
);
143 Time
Time::FromFileTime(FILETIME ft
) {
144 if (bit_cast
<int64
, FILETIME
>(ft
) == 0)
146 if (ft
.dwHighDateTime
== std::numeric_limits
<DWORD
>::max() &&
147 ft
.dwLowDateTime
== std::numeric_limits
<DWORD
>::max())
149 return Time(FileTimeToMicroseconds(ft
));
152 FILETIME
Time::ToFileTime() const {
154 return bit_cast
<FILETIME
, int64
>(0);
157 result
.dwHighDateTime
= std::numeric_limits
<DWORD
>::max();
158 result
.dwLowDateTime
= std::numeric_limits
<DWORD
>::max();
162 MicrosecondsToFileTime(us_
, &utc_ft
);
167 void Time::EnableHighResolutionTimer(bool enable
) {
168 // Test for single-threaded access.
169 static PlatformThreadId my_thread
= PlatformThread::CurrentId();
170 DCHECK(PlatformThread::CurrentId() == my_thread
);
172 if (high_resolution_timer_enabled_
== enable
)
175 high_resolution_timer_enabled_
= enable
;
179 bool Time::ActivateHighResolutionTimer(bool activating
) {
180 if (!high_resolution_timer_enabled_
&& activating
)
183 // Using anything other than 1ms makes timers granular
185 const int kMinTimerIntervalMs
= 1;
188 result
= timeBeginPeriod(kMinTimerIntervalMs
);
189 high_resolution_timer_activated_
++;
191 result
= timeEndPeriod(kMinTimerIntervalMs
);
192 high_resolution_timer_activated_
--;
194 return result
== TIMERR_NOERROR
;
198 bool Time::IsHighResolutionTimerInUse() {
199 // Note: we should track the high_resolution_timer_activated_ value
200 // under a lock if we want it to be accurate in a system with multiple
201 // message loops. We don't do that - because we don't want to take the
202 // expense of a lock for this. We *only* track this value so that unit
203 // tests can see if the high resolution timer is on or off.
204 return high_resolution_timer_enabled_
&&
205 high_resolution_timer_activated_
> 0;
209 Time
Time::FromExploded(bool is_local
, const Exploded
& exploded
) {
210 // Create the system struct representing our exploded time. It will either be
211 // in local time or UTC.
213 st
.wYear
= exploded
.year
;
214 st
.wMonth
= exploded
.month
;
215 st
.wDayOfWeek
= exploded
.day_of_week
;
216 st
.wDay
= exploded
.day_of_month
;
217 st
.wHour
= exploded
.hour
;
218 st
.wMinute
= exploded
.minute
;
219 st
.wSecond
= exploded
.second
;
220 st
.wMilliseconds
= exploded
.millisecond
;
224 // Ensure that it's in UTC.
227 success
= TzSpecificLocalTimeToSystemTime(NULL
, &st
, &utc_st
) &&
228 SystemTimeToFileTime(&utc_st
, &ft
);
230 success
= !!SystemTimeToFileTime(&st
, &ft
);
234 NOTREACHED() << "Unable to convert time";
237 return Time(FileTimeToMicroseconds(ft
));
240 void Time::Explode(bool is_local
, Exploded
* exploded
) const {
242 // We are not able to convert it to FILETIME.
243 ZeroMemory(exploded
, sizeof(*exploded
));
249 MicrosecondsToFileTime(us_
, &utc_ft
);
251 // FILETIME in local time if necessary.
253 // FILETIME in SYSTEMTIME (exploded).
257 // We don't use FileTimeToLocalFileTime here, since it uses the current
258 // settings for the time zone and daylight saving time. Therefore, if it is
259 // daylight saving time, it will take daylight saving time into account,
260 // even if the time you are converting is in standard time.
261 success
= FileTimeToSystemTime(&utc_ft
, &utc_st
) &&
262 SystemTimeToTzSpecificLocalTime(NULL
, &utc_st
, &st
);
264 success
= !!FileTimeToSystemTime(&utc_ft
, &st
);
268 NOTREACHED() << "Unable to convert time, don't know why";
269 ZeroMemory(exploded
, sizeof(*exploded
));
273 exploded
->year
= st
.wYear
;
274 exploded
->month
= st
.wMonth
;
275 exploded
->day_of_week
= st
.wDayOfWeek
;
276 exploded
->day_of_month
= st
.wDay
;
277 exploded
->hour
= st
.wHour
;
278 exploded
->minute
= st
.wMinute
;
279 exploded
->second
= st
.wSecond
;
280 exploded
->millisecond
= st
.wMilliseconds
;
283 // TimeTicks ------------------------------------------------------------------
286 // We define a wrapper to adapt between the __stdcall and __cdecl call of the
287 // mock function, and to avoid a static constructor. Assigning an import to a
288 // function pointer directly would require setup code to fetch from the IAT.
289 DWORD
timeGetTimeWrapper() {
290 return timeGetTime();
293 DWORD (*tick_function
)(void) = &timeGetTimeWrapper
;
295 // Accumulation of time lost due to rollover (in milliseconds).
296 int64 rollover_ms
= 0;
298 // The last timeGetTime value we saw, to detect rollover.
299 DWORD last_seen_now
= 0;
301 // Lock protecting rollover_ms and last_seen_now.
302 // Note: this is a global object, and we usually avoid these. However, the time
303 // code is low-level, and we don't want to use Singletons here (it would be too
304 // easy to use a Singleton without even knowing it, and that may lead to many
305 // gotchas). Its impact on startup time should be negligible due to low-level
306 // nature of time code.
307 base::Lock rollover_lock
;
309 // We use timeGetTime() to implement TimeTicks::Now(). This can be problematic
310 // because it returns the number of milliseconds since Windows has started,
311 // which will roll over the 32-bit value every ~49 days. We try to track
312 // rollover ourselves, which works if TimeTicks::Now() is called at least every
314 TimeDelta
RolloverProtectedNow() {
315 base::AutoLock
locked(rollover_lock
);
316 // We should hold the lock while calling tick_function to make sure that
317 // we keep last_seen_now stay correctly in sync.
318 DWORD now
= tick_function();
319 if (now
< last_seen_now
)
320 rollover_ms
+= 0x100000000I
64; // ~49.7 days.
322 return TimeDelta::FromMilliseconds(now
+ rollover_ms
);
325 // Overview of time counters:
326 // (1) CPU cycle counter. (Retrieved via RDTSC)
327 // The CPU counter provides the highest resolution time stamp and is the least
328 // expensive to retrieve. However, the CPU counter is unreliable and should not
329 // be used in production. Its biggest issue is that it is per processor and it
330 // is not synchronized between processors. Also, on some computers, the counters
331 // will change frequency due to thermal and power changes, and stop in some
334 // (2) QueryPerformanceCounter (QPC). The QPC counter provides a high-
335 // resolution (100 nanoseconds) time stamp but is comparatively more expensive
336 // to retrieve. What QueryPerformanceCounter actually does is up to the HAL.
337 // (with some help from ACPI).
338 // According to http://blogs.msdn.com/oldnewthing/archive/2005/09/02/459952.aspx
339 // in the worst case, it gets the counter from the rollover interrupt on the
340 // programmable interrupt timer. In best cases, the HAL may conclude that the
341 // RDTSC counter runs at a constant frequency, then it uses that instead. On
342 // multiprocessor machines, it will try to verify the values returned from
343 // RDTSC on each processor are consistent with each other, and apply a handful
344 // of workarounds for known buggy hardware. In other words, QPC is supposed to
345 // give consistent result on a multiprocessor computer, but it is unreliable in
346 // reality due to bugs in BIOS or HAL on some, especially old computers.
347 // With recent updates on HAL and newer BIOS, QPC is getting more reliable but
348 // it should be used with caution.
350 // (3) System time. The system time provides a low-resolution (typically 10ms
351 // to 55 milliseconds) time stamp but is comparatively less expensive to
352 // retrieve and more reliable.
353 class HighResNowSingleton
{
355 static HighResNowSingleton
* GetInstance() {
356 return Singleton
<HighResNowSingleton
>::get();
359 bool IsUsingHighResClock() {
360 return ticks_per_second_
!= 0.0;
363 void DisableHighResClock() {
364 ticks_per_second_
= 0.0;
368 if (IsUsingHighResClock())
369 return TimeDelta::FromMicroseconds(UnreliableNow());
371 // Just fallback to the slower clock.
372 return RolloverProtectedNow();
375 int64
GetQPCDriftMicroseconds() {
376 if (!IsUsingHighResClock())
378 return abs((UnreliableNow() - ReliableNow()) - skew_
);
381 int64
QPCValueToMicroseconds(LONGLONG qpc_value
) {
382 if (!ticks_per_second_
)
385 // Intentionally calculate microseconds in a round about manner to avoid
386 // overflow and precision issues. Think twice before simplifying!
387 int64 whole_seconds
= qpc_value
/ ticks_per_second_
;
388 int64 leftover_ticks
= qpc_value
% ticks_per_second_
;
389 int64 microseconds
= (whole_seconds
* Time::kMicrosecondsPerSecond
) +
390 ((leftover_ticks
* Time::kMicrosecondsPerSecond
) /
396 HighResNowSingleton()
397 : ticks_per_second_(0),
401 // On Athlon X2 CPUs (e.g. model 15) QueryPerformanceCounter is
402 // unreliable. Fallback to low-res clock.
404 if (cpu
.vendor_name() == "AuthenticAMD" && cpu
.family() == 15)
405 DisableHighResClock();
408 // Synchronize the QPC clock with GetSystemTimeAsFileTime.
409 void InitializeClock() {
410 LARGE_INTEGER ticks_per_sec
= {0};
411 if (!QueryPerformanceFrequency(&ticks_per_sec
))
412 return; // Broken, we don't guarantee this function works.
413 ticks_per_second_
= ticks_per_sec
.QuadPart
;
415 skew_
= UnreliableNow() - ReliableNow();
418 // Get the number of microseconds since boot in an unreliable fashion.
419 int64
UnreliableNow() {
421 QueryPerformanceCounter(&now
);
422 return QPCValueToMicroseconds(now
.QuadPart
);
425 // Get the number of microseconds since boot in a reliable fashion.
426 int64
ReliableNow() {
427 return RolloverProtectedNow().InMicroseconds();
430 int64 ticks_per_second_
; // 0 indicates QPF failed and we're broken.
431 int64 skew_
; // Skew between lo-res and hi-res clocks (for debugging).
433 friend struct DefaultSingletonTraits
<HighResNowSingleton
>;
439 TimeTicks::TickFunctionType
TimeTicks::SetMockTickFunction(
440 TickFunctionType ticker
) {
441 base::AutoLock
locked(rollover_lock
);
442 TickFunctionType old
= tick_function
;
443 tick_function
= ticker
;
450 TimeTicks
TimeTicks::Now() {
451 return TimeTicks() + RolloverProtectedNow();
455 TimeTicks
TimeTicks::HighResNow() {
456 return TimeTicks() + HighResNowSingleton::GetInstance()->Now();
460 TimeTicks
TimeTicks::NowFromSystemTraceTime() {
465 int64
TimeTicks::GetQPCDriftMicroseconds() {
466 return HighResNowSingleton::GetInstance()->GetQPCDriftMicroseconds();
470 TimeTicks
TimeTicks::FromQPCValue(LONGLONG qpc_value
) {
472 HighResNowSingleton::GetInstance()->QPCValueToMicroseconds(qpc_value
));
476 bool TimeTicks::IsHighResClockWorking() {
477 return HighResNowSingleton::GetInstance()->IsUsingHighResClock();
480 // TimeDelta ------------------------------------------------------------------
483 TimeDelta
TimeDelta::FromQPCValue(LONGLONG qpc_value
) {
485 HighResNowSingleton::GetInstance()->QPCValueToMicroseconds(qpc_value
));