1 // Copyright (c) 2011 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/logging.h"
45 #include "base/cpu.h"
46 #include "base/memory/singleton.h"
47 #include "base/synchronization/lock.h"
48
49 using base::Time;
50 using base::TimeDelta;
51 using base::TimeTicks;
52
53 namespace {
54
55 // From MSDN, FILETIME "Contains a 64-bit value representing the number of
56 // 100-nanosecond intervals since January 1, 1601 (UTC)."
FileTimeToMicroseconds(const FILETIME & ft)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
60 // machines.
61 return bit_cast<int64, FILETIME>(ft) / 10;
62 }
63
MicrosecondsToFileTime(int64 us,FILETIME * ft)64 void 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
CurrentWallclockMicroseconds()73 int64 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.
80 const int kMaxMillisecondsToAvoidDrift = 60 * Time::kMillisecondsPerSecond;
81
82 int64 initial_time = 0;
83 TimeTicks initial_ticks;
84
InitializeClock()85 void 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
99 const int64 Time::kTimeTToMicrosecondsOffset = GG_INT64_C(11644473600000000);
100
101 bool Time::high_resolution_timer_enabled_ = false;
102
103 // static
Now()104 Time 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
NowFromSystemTime()135 Time Time::NowFromSystemTime() {
136 // Force resync.
137 InitializeClock();
138 return Time(initial_time);
139 }
140
141 // static
FromFileTime(FILETIME ft)142 Time Time::FromFileTime(FILETIME ft) {
143 return Time(FileTimeToMicroseconds(ft));
144 }
145
ToFileTime() const146 FILETIME Time::ToFileTime() const {
147 FILETIME utc_ft;
148 MicrosecondsToFileTime(us_, &utc_ft);
149 return utc_ft;
150 }
151
152 // static
EnableHighResolutionTimer(bool enable)153 void 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
ActivateHighResolutionTimer(bool activate)165 bool 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
FromExploded(bool is_local,const Exploded & exploded)181 Time 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
Explode(bool is_local,Exploded * exploded) const210 void 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 ------------------------------------------------------------------
242 namespace {
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.
timeGetTimeWrapper()247 DWORD timeGetTimeWrapper() {
248 return timeGetTime();
249 }
250
251 DWORD (*tick_function)(void) = &timeGetTimeWrapper;
252
253 // Accumulation of time lost due to rollover (in milliseconds).
254 int64 rollover_ms = 0;
255
256 // The last timeGetTime value we saw, to detect rollover.
257 DWORD 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.
265 base::Lock 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.
RolloverProtectedNow()272 TimeDelta RolloverProtectedNow() {
273 base::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.
311 class HighResNowSingleton {
312 public:
GetInstance()313 static HighResNowSingleton* GetInstance() {
314 return Singleton<HighResNowSingleton>::get();
315 }
316
IsUsingHighResClock()317 bool IsUsingHighResClock() {
318 return ticks_per_microsecond_ != 0.0;
319 }
320
DisableHighResClock()321 void DisableHighResClock() {
322 ticks_per_microsecond_ = 0.0;
323 }
324
Now()325 TimeDelta Now() {
326 if (IsUsingHighResClock())
327 return TimeDelta::FromMicroseconds(UnreliableNow());
328
329 // Just fallback to the slower clock.
330 return RolloverProtectedNow();
331 }
332
GetQPCDriftMicroseconds()333 int64 GetQPCDriftMicroseconds() {
334 if (!IsUsingHighResClock())
335 return 0;
336
337 return abs((UnreliableNow() - ReliableNow()) - skew_);
338 }
339
340 private:
HighResNowSingleton()341 HighResNowSingleton()
342 : ticks_per_microsecond_(0.0),
343 skew_(0) {
344 InitializeClock();
345
346 // On Athlon X2 CPUs (e.g. model 15) QueryPerformanceCounter is
347 // unreliable. Fallback to low-res clock.
348 base::CPU cpu;
349 if (cpu.vendor_name() == "AuthenticAMD" && cpu.family() == 15)
350 DisableHighResClock();
351 }
352
353 // Synchronize the QPC clock with GetSystemTimeAsFileTime.
InitializeClock()354 void InitializeClock() {
355 LARGE_INTEGER ticks_per_sec = {0};
356 if (!QueryPerformanceFrequency(&ticks_per_sec))
357 return; // Broken, we don't guarantee this function works.
358 ticks_per_microsecond_ = static_cast<float>(ticks_per_sec.QuadPart) /
359 static_cast<float>(Time::kMicrosecondsPerSecond);
360
361 skew_ = UnreliableNow() - ReliableNow();
362 }
363
364 // Get the number of microseconds since boot in an unreliable fashion.
UnreliableNow()365 int64 UnreliableNow() {
366 LARGE_INTEGER now;
367 QueryPerformanceCounter(&now);
368 return static_cast<int64>(now.QuadPart / ticks_per_microsecond_);
369 }
370
371 // Get the number of microseconds since boot in a reliable fashion.
ReliableNow()372 int64 ReliableNow() {
373 return RolloverProtectedNow().InMicroseconds();
374 }
375
376 // Cached clock frequency -> microseconds. This assumes that the clock
377 // frequency is faster than one microsecond (which is 1MHz, should be OK).
378 float ticks_per_microsecond_; // 0 indicates QPF failed and we're broken.
379 int64 skew_; // Skew between lo-res and hi-res clocks (for debugging).
380
381 friend struct DefaultSingletonTraits<HighResNowSingleton>;
382 };
383
384 } // namespace
385
386 // static
SetMockTickFunction(TickFunctionType ticker)387 TimeTicks::TickFunctionType TimeTicks::SetMockTickFunction(
388 TickFunctionType ticker) {
389 TickFunctionType old = tick_function;
390 tick_function = ticker;
391 return old;
392 }
393
394 // static
Now()395 TimeTicks TimeTicks::Now() {
396 return TimeTicks() + RolloverProtectedNow();
397 }
398
399 // static
HighResNow()400 TimeTicks TimeTicks::HighResNow() {
401 return TimeTicks() + HighResNowSingleton::GetInstance()->Now();
402 }
403
404 // static
GetQPCDriftMicroseconds()405 int64 TimeTicks::GetQPCDriftMicroseconds() {
406 return HighResNowSingleton::GetInstance()->GetQPCDriftMicroseconds();
407 }
408
409 // static
IsHighResClockWorking()410 bool TimeTicks::IsHighResClockWorking() {
411 return HighResNowSingleton::GetInstance()->IsUsingHighResClock();
412 }
413