time_win.cc revision c407dc5cd9bdc5668497f21b26b09d988ab439de
1// Copyright (c) 2009 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. 4 5 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 10// 11// The default windows timer, GetSystemTimeAsFileTime is not very precise. 12// It is only good to ~15.5ms. 13// 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. 20// 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 29// 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. 36 37#include "base/time.h" 38 39#pragma comment(lib, "winmm.lib") 40#include <windows.h> 41#include <mmsystem.h> 42 43#include "base/basictypes.h" 44#include "base/lock.h" 45#include "base/logging.h" 46#include "base/cpu.h" 47#include "base/singleton.h" 48 49using base::Time; 50using base::TimeDelta; 51using base::TimeTicks; 52 53namespace { 54 55// From MSDN, FILETIME "Contains a 64-bit value representing the number of 56// 100-nanosecond intervals since January 1, 1601 (UTC)." 57int64 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 60 // machines. 61 return bit_cast<int64, FILETIME>(ft) / 10; 62} 63 64void MicrosecondsToFileTime(int64 us, FILETIME* ft) { 65 DCHECK(us >= 0) << "Time is less than 0, negative values are not " 66 "representable in FILETIME"; 67 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); 71} 72 73int64 CurrentWallclockMicroseconds() { 74 FILETIME ft; 75 ::GetSystemTimeAsFileTime(&ft); 76 return FileTimeToMicroseconds(ft); 77} 78 79// Time between resampling the un-granular clock for this API. 60 seconds. 80const int kMaxMillisecondsToAvoidDrift = 60 * Time::kMillisecondsPerSecond; 81 82int64 initial_time = 0; 83TimeTicks initial_ticks; 84 85void InitializeClock() { 86 initial_ticks = TimeTicks::Now(); 87 initial_time = CurrentWallclockMicroseconds(); 88} 89 90} // namespace 91 92// Time ----------------------------------------------------------------------- 93 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. 98// static 99const int64 Time::kTimeTToMicrosecondsOffset = GG_INT64_C(11644473600000000); 100 101bool Time::high_resolution_timer_enabled_ = false; 102 103// static 104Time Time::Now() { 105 if (initial_time == 0) 106 InitializeClock(); 107 108 // We implement time using the high-resolution timers so that we can get 109 // timeouts which are smaller than 10-15ms. If we just used 110 // CurrentWallclockMicroseconds(), we'd have the less-granular timer. 111 // 112 // To make this work, we initialize the clock (initial_time) and the 113 // counter (initial_ctr). To compute the initial time, we can check 114 // the number of ticks that have elapsed, and compute the delta. 115 // 116 // To avoid any drift, we periodically resync the counters to the system 117 // clock. 118 while (true) { 119 TimeTicks ticks = TimeTicks::Now(); 120 121 // Calculate the time elapsed since we started our timer 122 TimeDelta elapsed = ticks - initial_ticks; 123 124 // Check if enough time has elapsed that we need to resync the clock. 125 if (elapsed.InMilliseconds() > kMaxMillisecondsToAvoidDrift) { 126 InitializeClock(); 127 continue; 128 } 129 130 return Time(elapsed + Time(initial_time)); 131 } 132} 133 134// static 135Time Time::NowFromSystemTime() { 136 // Force resync. 137 InitializeClock(); 138 return Time(initial_time); 139} 140 141// static 142Time Time::FromFileTime(FILETIME ft) { 143 return Time(FileTimeToMicroseconds(ft)); 144} 145 146FILETIME Time::ToFileTime() const { 147 FILETIME utc_ft; 148 MicrosecondsToFileTime(us_, &utc_ft); 149 return utc_ft; 150} 151 152// static 153void Time::EnableHighResolutionTimer(bool enable) { 154 // Test for single-threaded access. 155 static PlatformThreadId my_thread = PlatformThread::CurrentId(); 156 DCHECK(PlatformThread::CurrentId() == my_thread); 157 158 if (high_resolution_timer_enabled_ == enable) 159 return; 160 161 high_resolution_timer_enabled_ = enable; 162} 163 164// static 165bool Time::ActivateHighResolutionTimer(bool activate) { 166 if (!high_resolution_timer_enabled_) 167 return false; 168 169 // Using anything other than 1ms makes timers granular 170 // to that interval. 171 const int kMinTimerIntervalMs = 1; 172 MMRESULT result; 173 if (activate) 174 result = timeBeginPeriod(kMinTimerIntervalMs); 175 else 176 result = timeEndPeriod(kMinTimerIntervalMs); 177 return result == TIMERR_NOERROR; 178} 179 180// static 181Time Time::FromExploded(bool is_local, const Exploded& exploded) { 182 // Create the system struct representing our exploded time. It will either be 183 // in local time or UTC. 184 SYSTEMTIME st; 185 st.wYear = exploded.year; 186 st.wMonth = exploded.month; 187 st.wDayOfWeek = exploded.day_of_week; 188 st.wDay = exploded.day_of_month; 189 st.wHour = exploded.hour; 190 st.wMinute = exploded.minute; 191 st.wSecond = exploded.second; 192 st.wMilliseconds = exploded.millisecond; 193 194 // Convert to FILETIME. 195 FILETIME ft; 196 if (!SystemTimeToFileTime(&st, &ft)) { 197 NOTREACHED() << "Unable to convert time"; 198 return Time(0); 199 } 200 201 // Ensure that it's in UTC. 202 if (is_local) { 203 FILETIME utc_ft; 204 LocalFileTimeToFileTime(&ft, &utc_ft); 205 return Time(FileTimeToMicroseconds(utc_ft)); 206 } 207 return Time(FileTimeToMicroseconds(ft)); 208} 209 210void Time::Explode(bool is_local, Exploded* exploded) const { 211 // FILETIME in UTC. 212 FILETIME utc_ft; 213 MicrosecondsToFileTime(us_, &utc_ft); 214 215 // FILETIME in local time if necessary. 216 BOOL success = TRUE; 217 FILETIME ft; 218 if (is_local) 219 success = FileTimeToLocalFileTime(&utc_ft, &ft); 220 else 221 ft = utc_ft; 222 223 // FILETIME in SYSTEMTIME (exploded). 224 SYSTEMTIME st; 225 if (!success || !FileTimeToSystemTime(&ft, &st)) { 226 NOTREACHED() << "Unable to convert time, don't know why"; 227 ZeroMemory(exploded, sizeof(exploded)); 228 return; 229 } 230 231 exploded->year = st.wYear; 232 exploded->month = st.wMonth; 233 exploded->day_of_week = st.wDayOfWeek; 234 exploded->day_of_month = st.wDay; 235 exploded->hour = st.wHour; 236 exploded->minute = st.wMinute; 237 exploded->second = st.wSecond; 238 exploded->millisecond = st.wMilliseconds; 239} 240 241// TimeTicks ------------------------------------------------------------------ 242namespace { 243 244// We define a wrapper to adapt between the __stdcall and __cdecl call of the 245// mock function, and to avoid a static constructor. Assigning an import to a 246// function pointer directly would require setup code to fetch from the IAT. 247DWORD timeGetTimeWrapper() { 248 return timeGetTime(); 249} 250 251DWORD (*tick_function)(void) = &timeGetTimeWrapper; 252 253// Accumulation of time lost due to rollover (in milliseconds). 254int64 rollover_ms = 0; 255 256// The last timeGetTime value we saw, to detect rollover. 257DWORD last_seen_now = 0; 258 259// Lock protecting rollover_ms and last_seen_now. 260// Note: this is a global object, and we usually avoid these. However, the time 261// code is low-level, and we don't want to use Singletons here (it would be too 262// easy to use a Singleton without even knowing it, and that may lead to many 263// gotchas). Its impact on startup time should be negligible due to low-level 264// nature of time code. 265Lock rollover_lock; 266 267// We use timeGetTime() to implement TimeTicks::Now(). This can be problematic 268// because it returns the number of milliseconds since Windows has started, 269// which will roll over the 32-bit value every ~49 days. We try to track 270// rollover ourselves, which works if TimeTicks::Now() is called at least every 271// 49 days. 272TimeDelta RolloverProtectedNow() { 273 AutoLock locked(rollover_lock); 274 // We should hold the lock while calling tick_function to make sure that 275 // we keep last_seen_now stay correctly in sync. 276 DWORD now = tick_function(); 277 if (now < last_seen_now) 278 rollover_ms += 0x100000000I64; // ~49.7 days. 279 last_seen_now = now; 280 return TimeDelta::FromMilliseconds(now + rollover_ms); 281} 282 283// Overview of time counters: 284// (1) CPU cycle counter. (Retrieved via RDTSC) 285// The CPU counter provides the highest resolution time stamp and is the least 286// expensive to retrieve. However, the CPU counter is unreliable and should not 287// be used in production. Its biggest issue is that it is per processor and it 288// is not synchronized between processors. Also, on some computers, the counters 289// will change frequency due to thermal and power changes, and stop in some 290// states. 291// 292// (2) QueryPerformanceCounter (QPC). The QPC counter provides a high- 293// resolution (100 nanoseconds) time stamp but is comparatively more expensive 294// to retrieve. What QueryPerformanceCounter actually does is up to the HAL. 295// (with some help from ACPI). 296// According to http://blogs.msdn.com/oldnewthing/archive/2005/09/02/459952.aspx 297// in the worst case, it gets the counter from the rollover interrupt on the 298// programmable interrupt timer. In best cases, the HAL may conclude that the 299// RDTSC counter runs at a constant frequency, then it uses that instead. On 300// multiprocessor machines, it will try to verify the values returned from 301// RDTSC on each processor are consistent with each other, and apply a handful 302// of workarounds for known buggy hardware. In other words, QPC is supposed to 303// give consistent result on a multiprocessor computer, but it is unreliable in 304// reality due to bugs in BIOS or HAL on some, especially old computers. 305// With recent updates on HAL and newer BIOS, QPC is getting more reliable but 306// it should be used with caution. 307// 308// (3) System time. The system time provides a low-resolution (typically 10ms 309// to 55 milliseconds) time stamp but is comparatively less expensive to 310// retrieve and more reliable. 311class HighResNowSingleton { 312 public: 313 HighResNowSingleton() 314 : ticks_per_microsecond_(0.0), 315 skew_(0) { 316 InitializeClock(); 317 318 // On Athlon X2 CPUs (e.g. model 15) QueryPerformanceCounter is 319 // unreliable. Fallback to low-res clock. 320 base::CPU cpu; 321 if (cpu.vendor_name() == "AuthenticAMD" && cpu.family() == 15) 322 DisableHighResClock(); 323 } 324 325 bool IsUsingHighResClock() { 326 return ticks_per_microsecond_ != 0.0; 327 } 328 329 void DisableHighResClock() { 330 ticks_per_microsecond_ = 0.0; 331 } 332 333 TimeDelta Now() { 334 // Our maximum tolerance for QPC drifting. 335 const int kMaxTimeDrift = 50 * Time::kMicrosecondsPerMillisecond; 336 337 if (IsUsingHighResClock()) { 338 int64 now = UnreliableNow(); 339 340 // Verify that QPC does not seem to drift. 341 DCHECK(now - ReliableNow() - skew_ < kMaxTimeDrift); 342 343 return TimeDelta::FromMicroseconds(now); 344 } 345 346 // Just fallback to the slower clock. 347 return RolloverProtectedNow(); 348 } 349 350 private: 351 // Synchronize the QPC clock with GetSystemTimeAsFileTime. 352 void InitializeClock() { 353 LARGE_INTEGER ticks_per_sec = {0}; 354 if (!QueryPerformanceFrequency(&ticks_per_sec)) 355 return; // Broken, we don't guarantee this function works. 356 ticks_per_microsecond_ = static_cast<float>(ticks_per_sec.QuadPart) / 357 static_cast<float>(Time::kMicrosecondsPerSecond); 358 359 skew_ = UnreliableNow() - ReliableNow(); 360 } 361 362 // Get the number of microseconds since boot in an unreliable fashion. 363 int64 UnreliableNow() { 364 LARGE_INTEGER now; 365 QueryPerformanceCounter(&now); 366 return static_cast<int64>(now.QuadPart / ticks_per_microsecond_); 367 } 368 369 // Get the number of microseconds since boot in a reliable fashion. 370 int64 ReliableNow() { 371 return RolloverProtectedNow().InMicroseconds(); 372 } 373 374 // Cached clock frequency -> microseconds. This assumes that the clock 375 // frequency is faster than one microsecond (which is 1MHz, should be OK). 376 float ticks_per_microsecond_; // 0 indicates QPF failed and we're broken. 377 int64 skew_; // Skew between lo-res and hi-res clocks (for debugging). 378 379 DISALLOW_COPY_AND_ASSIGN(HighResNowSingleton); 380}; 381 382} // namespace 383 384// static 385TimeTicks::TickFunctionType TimeTicks::SetMockTickFunction( 386 TickFunctionType ticker) { 387 TickFunctionType old = tick_function; 388 tick_function = ticker; 389 return old; 390} 391 392// static 393TimeTicks TimeTicks::Now() { 394 return TimeTicks() + RolloverProtectedNow(); 395} 396 397// static 398TimeTicks TimeTicks::HighResNow() { 399 return TimeTicks() + Singleton<HighResNowSingleton>::get()->Now(); 400} 401