Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / base / time / time_win.cc
blob492b54a93f126717ad0b2c339e75322bdeeb1532
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
7 //
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.
34 #include "base/time/time.h"
36 #pragma comment(lib, "winmm.lib")
37 #include <windows.h>
38 #include <mmsystem.h>
40 #include "base/basictypes.h"
41 #include "base/cpu.h"
42 #include "base/lazy_instance.h"
43 #include "base/logging.h"
44 #include "base/synchronization/lock.h"
46 using base::Time;
47 using base::TimeDelta;
48 using base::TimeTicks;
50 namespace {
52 // From MSDN, FILETIME "Contains a 64-bit value representing the number of
53 // 100-nanosecond intervals since January 1, 1601 (UTC)."
54 int64 FileTimeToMicroseconds(const FILETIME& ft) {
55 // Need to bit_cast to fix alignment, then divide by 10 to convert
56 // 100-nanoseconds to milliseconds. This only works on little-endian
57 // machines.
58 return bit_cast<int64, FILETIME>(ft) / 10;
61 void MicrosecondsToFileTime(int64 us, FILETIME* ft) {
62 DCHECK_GE(us, 0LL) << "Time is less than 0, negative values are not "
63 "representable in FILETIME";
65 // Multiply by 10 to convert milliseconds to 100-nanoseconds. Bit_cast will
66 // handle alignment problems. This only works on little-endian machines.
67 *ft = bit_cast<FILETIME, int64>(us * 10);
70 int64 CurrentWallclockMicroseconds() {
71 FILETIME ft;
72 ::GetSystemTimeAsFileTime(&ft);
73 return FileTimeToMicroseconds(ft);
76 // Time between resampling the un-granular clock for this API. 60 seconds.
77 const int kMaxMillisecondsToAvoidDrift = 60 * Time::kMillisecondsPerSecond;
79 int64 initial_time = 0;
80 TimeTicks initial_ticks;
82 void InitializeClock() {
83 initial_ticks = TimeTicks::Now();
84 initial_time = CurrentWallclockMicroseconds();
87 // The two values that ActivateHighResolutionTimer uses to set the systemwide
88 // timer interrupt frequency on Windows. It controls how precise timers are
89 // but also has a big impact on battery life.
90 const int kMinTimerIntervalHighResMs = 1;
91 const int kMinTimerIntervalLowResMs = 4;
92 // Track if kMinTimerIntervalHighResMs or kMinTimerIntervalLowResMs is active.
93 bool g_high_res_timer_enabled = false;
94 // How many times the high resolution timer has been called.
95 int g_high_res_timer_count = 0;
96 // The lock to control access to the above two variables.
97 base::LazyInstance<base::Lock>::Leaky g_high_res_lock =
98 LAZY_INSTANCE_INITIALIZER;
100 } // namespace
102 // Time -----------------------------------------------------------------------
104 // The internal representation of Time uses FILETIME, whose epoch is 1601-01-01
105 // 00:00:00 UTC. ((1970-1601)*365+89)*24*60*60*1000*1000, where 89 is the
106 // number of leap year days between 1601 and 1970: (1970-1601)/4 excluding
107 // 1700, 1800, and 1900.
108 // static
109 const int64 Time::kTimeTToMicrosecondsOffset = GG_INT64_C(11644473600000000);
111 // static
112 Time Time::Now() {
113 if (initial_time == 0)
114 InitializeClock();
116 // We implement time using the high-resolution timers so that we can get
117 // timeouts which are smaller than 10-15ms. If we just used
118 // CurrentWallclockMicroseconds(), we'd have the less-granular timer.
120 // To make this work, we initialize the clock (initial_time) and the
121 // counter (initial_ctr). To compute the initial time, we can check
122 // the number of ticks that have elapsed, and compute the delta.
124 // To avoid any drift, we periodically resync the counters to the system
125 // clock.
126 while (true) {
127 TimeTicks ticks = TimeTicks::Now();
129 // Calculate the time elapsed since we started our timer
130 TimeDelta elapsed = ticks - initial_ticks;
132 // Check if enough time has elapsed that we need to resync the clock.
133 if (elapsed.InMilliseconds() > kMaxMillisecondsToAvoidDrift) {
134 InitializeClock();
135 continue;
138 return Time(elapsed + Time(initial_time));
142 // static
143 Time Time::NowFromSystemTime() {
144 // Force resync.
145 InitializeClock();
146 return Time(initial_time);
149 // static
150 Time Time::FromFileTime(FILETIME ft) {
151 if (bit_cast<int64, FILETIME>(ft) == 0)
152 return Time();
153 if (ft.dwHighDateTime == std::numeric_limits<DWORD>::max() &&
154 ft.dwLowDateTime == std::numeric_limits<DWORD>::max())
155 return Max();
156 return Time(FileTimeToMicroseconds(ft));
159 FILETIME Time::ToFileTime() const {
160 if (is_null())
161 return bit_cast<FILETIME, int64>(0);
162 if (is_max()) {
163 FILETIME result;
164 result.dwHighDateTime = std::numeric_limits<DWORD>::max();
165 result.dwLowDateTime = std::numeric_limits<DWORD>::max();
166 return result;
168 FILETIME utc_ft;
169 MicrosecondsToFileTime(us_, &utc_ft);
170 return utc_ft;
173 // static
174 void Time::EnableHighResolutionTimer(bool enable) {
175 base::AutoLock lock(g_high_res_lock.Get());
176 if (g_high_res_timer_enabled == enable)
177 return;
178 g_high_res_timer_enabled = enable;
179 if (!g_high_res_timer_count)
180 return;
181 // Since g_high_res_timer_count != 0, an ActivateHighResolutionTimer(true)
182 // was called which called timeBeginPeriod with g_high_res_timer_enabled
183 // with a value which is the opposite of |enable|. With that information we
184 // call timeEndPeriod with the same value used in timeBeginPeriod and
185 // therefore undo the period effect.
186 if (enable) {
187 timeEndPeriod(kMinTimerIntervalLowResMs);
188 timeBeginPeriod(kMinTimerIntervalHighResMs);
189 } else {
190 timeEndPeriod(kMinTimerIntervalHighResMs);
191 timeBeginPeriod(kMinTimerIntervalLowResMs);
195 // static
196 bool Time::ActivateHighResolutionTimer(bool activating) {
197 // We only do work on the transition from zero to one or one to zero so we
198 // can easily undo the effect (if necessary) when EnableHighResolutionTimer is
199 // called.
200 base::AutoLock lock(g_high_res_lock.Get());
201 UINT period = g_high_res_timer_enabled ? kMinTimerIntervalHighResMs
202 : kMinTimerIntervalLowResMs;
203 int high_res_count =
204 activating ? ++g_high_res_timer_count : --g_high_res_timer_count;
206 if (activating) {
207 if (high_res_count == 1)
208 timeBeginPeriod(period);
209 } else {
210 if (high_res_count == 0)
211 timeEndPeriod(period);
213 return (period == kMinTimerIntervalHighResMs);
216 // static
217 bool Time::IsHighResolutionTimerInUse() {
218 base::AutoLock lock(g_high_res_lock.Get());
219 return g_high_res_timer_enabled && g_high_res_timer_count > 0;
222 // static
223 Time Time::FromExploded(bool is_local, const Exploded& exploded) {
224 // Create the system struct representing our exploded time. It will either be
225 // in local time or UTC.
226 SYSTEMTIME st;
227 st.wYear = exploded.year;
228 st.wMonth = exploded.month;
229 st.wDayOfWeek = exploded.day_of_week;
230 st.wDay = exploded.day_of_month;
231 st.wHour = exploded.hour;
232 st.wMinute = exploded.minute;
233 st.wSecond = exploded.second;
234 st.wMilliseconds = exploded.millisecond;
236 FILETIME ft;
237 bool success = true;
238 // Ensure that it's in UTC.
239 if (is_local) {
240 SYSTEMTIME utc_st;
241 success = TzSpecificLocalTimeToSystemTime(NULL, &st, &utc_st) &&
242 SystemTimeToFileTime(&utc_st, &ft);
243 } else {
244 success = !!SystemTimeToFileTime(&st, &ft);
247 if (!success) {
248 NOTREACHED() << "Unable to convert time";
249 return Time(0);
251 return Time(FileTimeToMicroseconds(ft));
254 void Time::Explode(bool is_local, Exploded* exploded) const {
255 if (us_ < 0LL) {
256 // We are not able to convert it to FILETIME.
257 ZeroMemory(exploded, sizeof(*exploded));
258 return;
261 // FILETIME in UTC.
262 FILETIME utc_ft;
263 MicrosecondsToFileTime(us_, &utc_ft);
265 // FILETIME in local time if necessary.
266 bool success = true;
267 // FILETIME in SYSTEMTIME (exploded).
268 SYSTEMTIME st = {0};
269 if (is_local) {
270 SYSTEMTIME utc_st;
271 // We don't use FileTimeToLocalFileTime here, since it uses the current
272 // settings for the time zone and daylight saving time. Therefore, if it is
273 // daylight saving time, it will take daylight saving time into account,
274 // even if the time you are converting is in standard time.
275 success = FileTimeToSystemTime(&utc_ft, &utc_st) &&
276 SystemTimeToTzSpecificLocalTime(NULL, &utc_st, &st);
277 } else {
278 success = !!FileTimeToSystemTime(&utc_ft, &st);
281 if (!success) {
282 NOTREACHED() << "Unable to convert time, don't know why";
283 ZeroMemory(exploded, sizeof(*exploded));
284 return;
287 exploded->year = st.wYear;
288 exploded->month = st.wMonth;
289 exploded->day_of_week = st.wDayOfWeek;
290 exploded->day_of_month = st.wDay;
291 exploded->hour = st.wHour;
292 exploded->minute = st.wMinute;
293 exploded->second = st.wSecond;
294 exploded->millisecond = st.wMilliseconds;
297 // TimeTicks ------------------------------------------------------------------
298 namespace {
300 // We define a wrapper to adapt between the __stdcall and __cdecl call of the
301 // mock function, and to avoid a static constructor. Assigning an import to a
302 // function pointer directly would require setup code to fetch from the IAT.
303 DWORD timeGetTimeWrapper() {
304 return timeGetTime();
307 DWORD (*tick_function)(void) = &timeGetTimeWrapper;
309 // Accumulation of time lost due to rollover (in milliseconds).
310 int64 rollover_ms = 0;
312 // The last timeGetTime value we saw, to detect rollover.
313 DWORD last_seen_now = 0;
315 // Lock protecting rollover_ms and last_seen_now.
316 // Note: this is a global object, and we usually avoid these. However, the time
317 // code is low-level, and we don't want to use Singletons here (it would be too
318 // easy to use a Singleton without even knowing it, and that may lead to many
319 // gotchas). Its impact on startup time should be negligible due to low-level
320 // nature of time code.
321 base::Lock rollover_lock;
323 // We use timeGetTime() to implement TimeTicks::Now(). This can be problematic
324 // because it returns the number of milliseconds since Windows has started,
325 // which will roll over the 32-bit value every ~49 days. We try to track
326 // rollover ourselves, which works if TimeTicks::Now() is called at least every
327 // 49 days.
328 TimeDelta RolloverProtectedNow() {
329 base::AutoLock locked(rollover_lock);
330 // We should hold the lock while calling tick_function to make sure that
331 // we keep last_seen_now stay correctly in sync.
332 DWORD now = tick_function();
333 if (now < last_seen_now)
334 rollover_ms += 0x100000000I64; // ~49.7 days.
335 last_seen_now = now;
336 return TimeDelta::FromMilliseconds(now + rollover_ms);
339 bool IsBuggyAthlon(const base::CPU& cpu) {
340 // On Athlon X2 CPUs (e.g. model 15) QueryPerformanceCounter is
341 // unreliable. Fallback to low-res clock.
342 return cpu.vendor_name() == "AuthenticAMD" && cpu.family() == 15;
345 // Overview of time counters:
346 // (1) CPU cycle counter. (Retrieved via RDTSC)
347 // The CPU counter provides the highest resolution time stamp and is the least
348 // expensive to retrieve. However, the CPU counter is unreliable and should not
349 // be used in production. Its biggest issue is that it is per processor and it
350 // is not synchronized between processors. Also, on some computers, the counters
351 // will change frequency due to thermal and power changes, and stop in some
352 // states.
354 // (2) QueryPerformanceCounter (QPC). The QPC counter provides a high-
355 // resolution (100 nanoseconds) time stamp but is comparatively more expensive
356 // to retrieve. What QueryPerformanceCounter actually does is up to the HAL.
357 // (with some help from ACPI).
358 // According to http://blogs.msdn.com/oldnewthing/archive/2005/09/02/459952.aspx
359 // in the worst case, it gets the counter from the rollover interrupt on the
360 // programmable interrupt timer. In best cases, the HAL may conclude that the
361 // RDTSC counter runs at a constant frequency, then it uses that instead. On
362 // multiprocessor machines, it will try to verify the values returned from
363 // RDTSC on each processor are consistent with each other, and apply a handful
364 // of workarounds for known buggy hardware. In other words, QPC is supposed to
365 // give consistent result on a multiprocessor computer, but it is unreliable in
366 // reality due to bugs in BIOS or HAL on some, especially old computers.
367 // With recent updates on HAL and newer BIOS, QPC is getting more reliable but
368 // it should be used with caution.
370 // (3) System time. The system time provides a low-resolution (typically 10ms
371 // to 55 milliseconds) time stamp but is comparatively less expensive to
372 // retrieve and more reliable.
373 class HighResNowSingleton {
374 public:
375 HighResNowSingleton()
376 : ticks_per_second_(0),
377 skew_(0) {
378 InitializeClock();
380 base::CPU cpu;
381 if (IsBuggyAthlon(cpu))
382 DisableHighResClock();
385 bool IsUsingHighResClock() {
386 return ticks_per_second_ != 0.0;
389 void DisableHighResClock() {
390 ticks_per_second_ = 0.0;
393 TimeDelta Now() {
394 if (IsUsingHighResClock())
395 return TimeDelta::FromMicroseconds(UnreliableNow());
397 // Just fallback to the slower clock.
398 return RolloverProtectedNow();
401 int64 GetQPCDriftMicroseconds() {
402 if (!IsUsingHighResClock())
403 return 0;
404 return abs((UnreliableNow() - ReliableNow()) - skew_);
407 int64 QPCValueToMicroseconds(LONGLONG qpc_value) {
408 if (!ticks_per_second_)
409 return 0;
410 // If the QPC Value is below the overflow threshold, we proceed with
411 // simple multiply and divide.
412 if (qpc_value < Time::kQPCOverflowThreshold)
413 return qpc_value * Time::kMicrosecondsPerSecond / ticks_per_second_;
414 // Otherwise, calculate microseconds in a round about manner to avoid
415 // overflow and precision issues.
416 int64 whole_seconds = qpc_value / ticks_per_second_;
417 int64 leftover_ticks = qpc_value - (whole_seconds * ticks_per_second_);
418 int64 microseconds = (whole_seconds * Time::kMicrosecondsPerSecond) +
419 ((leftover_ticks * Time::kMicrosecondsPerSecond) /
420 ticks_per_second_);
421 return microseconds;
424 private:
425 // Synchronize the QPC clock with GetSystemTimeAsFileTime.
426 void InitializeClock() {
427 LARGE_INTEGER ticks_per_sec = {0};
428 if (!QueryPerformanceFrequency(&ticks_per_sec))
429 return; // Broken, we don't guarantee this function works.
430 ticks_per_second_ = ticks_per_sec.QuadPart;
432 skew_ = UnreliableNow() - ReliableNow();
435 // Get the number of microseconds since boot in an unreliable fashion.
436 int64 UnreliableNow() {
437 LARGE_INTEGER now;
438 QueryPerformanceCounter(&now);
439 return QPCValueToMicroseconds(now.QuadPart);
442 // Get the number of microseconds since boot in a reliable fashion.
443 int64 ReliableNow() {
444 return RolloverProtectedNow().InMicroseconds();
447 int64 ticks_per_second_; // 0 indicates QPF failed and we're broken.
448 int64 skew_; // Skew between lo-res and hi-res clocks (for debugging).
451 static base::LazyInstance<HighResNowSingleton>::Leaky
452 leaky_high_res_now_singleton = LAZY_INSTANCE_INITIALIZER;
454 HighResNowSingleton* GetHighResNowSingleton() {
455 return leaky_high_res_now_singleton.Pointer();
458 TimeDelta HighResNowWrapper() {
459 return GetHighResNowSingleton()->Now();
462 typedef TimeDelta (*NowFunction)(void);
463 NowFunction now_function = RolloverProtectedNow;
465 bool CPUReliablySupportsHighResTime() {
466 base::CPU cpu;
467 if (!cpu.has_non_stop_time_stamp_counter() ||
468 !GetHighResNowSingleton()->IsUsingHighResClock())
469 return false;
471 if (IsBuggyAthlon(cpu))
472 return false;
474 return true;
477 } // namespace
479 // static
480 TimeTicks::TickFunctionType TimeTicks::SetMockTickFunction(
481 TickFunctionType ticker) {
482 base::AutoLock locked(rollover_lock);
483 TickFunctionType old = tick_function;
484 tick_function = ticker;
485 rollover_ms = 0;
486 last_seen_now = 0;
487 return old;
490 // static
491 bool TimeTicks::SetNowIsHighResNowIfSupported() {
492 if (!CPUReliablySupportsHighResTime()) {
493 return false;
496 now_function = HighResNowWrapper;
497 return true;
500 // static
501 TimeTicks TimeTicks::Now() {
502 return TimeTicks() + now_function();
505 // static
506 TimeTicks TimeTicks::HighResNow() {
507 return TimeTicks() + HighResNowWrapper();
510 // static
511 bool TimeTicks::IsHighResNowFastAndReliable() {
512 return CPUReliablySupportsHighResTime();
515 // static
516 TimeTicks TimeTicks::ThreadNow() {
517 NOTREACHED();
518 return TimeTicks();
521 // static
522 TimeTicks TimeTicks::NowFromSystemTraceTime() {
523 return HighResNow();
526 // static
527 int64 TimeTicks::GetQPCDriftMicroseconds() {
528 return GetHighResNowSingleton()->GetQPCDriftMicroseconds();
531 // static
532 TimeTicks TimeTicks::FromQPCValue(LONGLONG qpc_value) {
533 return TimeTicks(GetHighResNowSingleton()->QPCValueToMicroseconds(qpc_value));
536 // static
537 bool TimeTicks::IsHighResClockWorking() {
538 return GetHighResNowSingleton()->IsUsingHighResClock();
541 TimeTicks TimeTicks::UnprotectedNow() {
542 if (now_function == HighResNowWrapper) {
543 return Now();
544 } else {
545 return TimeTicks() + TimeDelta::FromMilliseconds(timeGetTime());
549 // TimeDelta ------------------------------------------------------------------
551 // static
552 TimeDelta TimeDelta::FromQPCValue(LONGLONG qpc_value) {
553 return TimeDelta(GetHighResNowSingleton()->QPCValueToMicroseconds(qpc_value));