88
99#include " vm/Time.h"
1010
11- #include " mozilla/DebugOnly.h"
12- #include " mozilla/MathAlgorithms.h"
13-
1411#ifdef SOLARIS
1512# define _REENTRANT 1
1613#endif
2219#ifdef XP_WIN
2320# include < windef.h>
2421# include < winbase.h>
25- # include < crtdbg.h> /* for _CrtSetReportMode */
26- # include < mmsystem.h> /* for timeBegin/EndPeriod */
27- # include < stdlib.h> /* for _set_invalid_parameter_handler */
22+ # include < crtdbg.h> /* for _CrtSetReportMode */
23+ # include < stdlib.h> /* for _set_invalid_parameter_handler */
2824#endif
2925
3026#ifdef XP_UNIX
@@ -37,8 +33,6 @@ extern int gettimeofday(struct timeval* tv);
3733
3834#endif /* XP_UNIX */
3935
40- using mozilla::DebugOnly;
41-
4236#if defined(XP_UNIX)
4337int64_t PRMJ_Now () {
4438 struct timeval tv;
@@ -54,6 +48,10 @@ int64_t PRMJ_Now() {
5448
5549#else
5650
51+ # if _WIN32_WINNT < _WIN32_WINNT_WIN8
52+ extern " C" WINBASEAPI void WINAPI GetSystemTimePreciseAsFileTime (LPFILETIME );
53+ # endif
54+
5755// Returns the number of microseconds since the Unix epoch.
5856static double FileTimeToUnixMicroseconds (const FILETIME & ft) {
5957 // Get the time in 100ns intervals.
@@ -68,167 +66,10 @@ static double FileTimeToUnixMicroseconds(const FILETIME& ft) {
6866 return double (t) * 0.1 ;
6967}
7068
71- struct CalibrationData {
72- double freq; /* The performance counter frequency */
73- double offset; /* The low res 'epoch' */
74- double timer_offset; /* The high res 'epoch' */
75-
76- bool calibrated;
77-
78- CRITICAL_SECTION data_lock;
79- };
80-
81- static CalibrationData calibration = {0 };
82-
83- static void NowCalibrate () {
84- MOZ_ASSERT (calibration.freq > 0 );
85-
86- // By wrapping a timeBegin/EndPeriod pair of calls around this loop,
87- // the loop seems to take much less time (1 ms vs 15ms) on Vista.
88- timeBeginPeriod (1 );
89- FILETIME ft, ftStart;
90- GetSystemTimeAsFileTime (&ftStart);
91- do {
92- GetSystemTimeAsFileTime (&ft);
93- } while (memcmp (&ftStart, &ft, sizeof (ft)) == 0 );
94- timeEndPeriod (1 );
95-
96- LARGE_INTEGER now;
97- QueryPerformanceCounter (&now);
98-
99- calibration.offset = FileTimeToUnixMicroseconds (ft);
100- calibration.timer_offset = double (now.QuadPart );
101- calibration.calibrated = true ;
102- }
103-
104- static const unsigned DataLockSpinCount = 4096 ;
105-
106- static void (WINAPI * pGetSystemTimePreciseAsFileTime)(LPFILETIME ) = nullptr;
107-
108- void PRMJ_NowInit () {
109- memset (&calibration, 0 , sizeof (calibration));
110-
111- // According to the documentation, QueryPerformanceFrequency will never
112- // return false or return a non-zero frequency on systems that run
113- // Windows XP or later. Also, the frequency is fixed so we only have to
114- // query it once.
115- LARGE_INTEGER liFreq;
116- DebugOnly<BOOL > res = QueryPerformanceFrequency (&liFreq);
117- MOZ_ASSERT (res);
118- calibration.freq = double (liFreq.QuadPart );
119- MOZ_ASSERT (calibration.freq > 0.0 );
120-
121- InitializeCriticalSectionAndSpinCount (&calibration.data_lock ,
122- DataLockSpinCount);
123-
124- // Windows 8 has a new API function we can use.
125- if (HMODULE h = GetModuleHandle (" kernel32.dll" )) {
126- pGetSystemTimePreciseAsFileTime = (void (WINAPI *)(LPFILETIME ))GetProcAddress (
127- h, " GetSystemTimePreciseAsFileTime" );
128- }
129- }
130-
131- void PRMJ_NowShutdown () { DeleteCriticalSection (&calibration.data_lock ); }
132-
133- # define MUTEX_LOCK (m ) EnterCriticalSection(m)
134- # define MUTEX_UNLOCK (m ) LeaveCriticalSection(m)
135- # define MUTEX_SETSPINCOUNT (m, c ) SetCriticalSectionSpinCount((m), (c))
136-
137- // Please see bug 363258 for why the win32 timing code is so complex.
138- static int64_t PRMJ_Now () {
139- if (pGetSystemTimePreciseAsFileTime) {
140- // Windows 8 has a new API function that does all the work.
141- FILETIME ft;
142- pGetSystemTimePreciseAsFileTime (&ft);
143- return int64_t (FileTimeToUnixMicroseconds (ft));
144- }
145-
146- bool calibrated = false ;
147- bool needsCalibration = !calibration.calibrated ;
148- double cachedOffset = 0.0 ;
149- while (true ) {
150- if (needsCalibration) {
151- MUTEX_LOCK (&calibration.data_lock );
152-
153- // Recalibrate only if no one else did before us.
154- if (calibration.offset == cachedOffset) {
155- // Since calibration can take a while, make any other
156- // threads immediately wait.
157- MUTEX_SETSPINCOUNT (&calibration.data_lock , 0 );
158-
159- NowCalibrate ();
160-
161- calibrated = true ;
162-
163- // Restore spin count.
164- MUTEX_SETSPINCOUNT (&calibration.data_lock , DataLockSpinCount);
165- }
166-
167- MUTEX_UNLOCK (&calibration.data_lock );
168- }
169-
170- // Calculate a low resolution time.
171- FILETIME ft;
172- GetSystemTimeAsFileTime (&ft);
173- double lowresTime = FileTimeToUnixMicroseconds (ft);
174-
175- // Grab high resolution time.
176- LARGE_INTEGER now;
177- QueryPerformanceCounter (&now);
178- double highresTimerValue = double (now.QuadPart );
179-
180- MUTEX_LOCK (&calibration.data_lock );
181- double highresTime = calibration.offset +
182- PRMJ_USEC_PER_SEC *
183- (highresTimerValue - calibration.timer_offset ) /
184- calibration.freq ;
185- cachedOffset = calibration.offset ;
186- MUTEX_UNLOCK (&calibration.data_lock );
187-
188- // Assume the NT kernel ticks every 15.6 ms. Unfortunately there's no
189- // good way to determine this (NtQueryTimerResolution is an undocumented
190- // API), but 15.6 ms seems to be the max possible value. Hardcoding 15.6
191- // means we'll recalibrate if the highres and lowres timers diverge by
192- // more than 30 ms.
193- static const double KernelTickInMicroseconds = 15625.25 ;
194-
195- // Check for clock skew.
196- double diff = lowresTime - highresTime;
197-
198- // For some reason that I have not determined, the skew can be
199- // up to twice a kernel tick. This does not seem to happen by
200- // itself, but I have only seen it triggered by another program
201- // doing some kind of file I/O. The symptoms are a negative diff
202- // followed by an equally large positive diff.
203- if (mozilla::Abs (diff) <= 2 * KernelTickInMicroseconds) {
204- // No detectable clock skew.
205- return int64_t (highresTime);
206- }
207-
208- if (calibrated) {
209- // If we already calibrated once this instance, and the
210- // clock is still skewed, then either the processor(s) are
211- // wildly changing clockspeed or the system is so busy that
212- // we get switched out for long periods of time. In either
213- // case, it would be infeasible to make use of high
214- // resolution results for anything, so let's resort to old
215- // behavior for this call. It's possible that in the
216- // future, the user will want the high resolution timer, so
217- // we don't disable it entirely.
218- return int64_t (lowresTime);
219- }
220-
221- // It is possible that when we recalibrate, we will return a
222- // value less than what we have returned before; this is
223- // unavoidable. We cannot tell the different between a
224- // faulty QueryPerformanceCounter implementation and user
225- // changes to the operating system time. Since we must
226- // respect user changes to the operating system time, we
227- // cannot maintain the invariant that Date.now() never
228- // decreases; the old implementation has this behavior as
229- // well.
230- needsCalibration = true ;
231- }
69+ int64_t PRMJ_Now () {
70+ FILETIME ft;
71+ GetSystemTimePreciseAsFileTime (&ft);
72+ return int64_t (FileTimeToUnixMicroseconds (ft));
23273}
23374#endif
23475
0 commit comments