Use ::QueryPerformanceCounter() for wxStopWatch implementation in wxMSW.
[wxWidgets.git] / src / common / stopwatch.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/stopwatch.cpp
3 // Purpose: wxStopWatch and other non-GUI stuff from wx/timer.h
4 // Author:
5 // Original version by Julian Smart
6 // Vadim Zeitlin got rid of all ifdefs (11.12.99)
7 // Sylvain Bougnoux added wxStopWatch class
8 // Guillermo Rodriguez <guille@iies.es> rewrote from scratch (Dic/99)
9 // Modified by:
10 // Created: 20.06.2003 (extracted from common/timercmn.cpp)
11 // RCS-ID: $Id$
12 // Copyright: (c) 1998-2003 wxWidgets Team
13 // Licence: wxWindows licence
14 ///////////////////////////////////////////////////////////////////////////////
15
16 // ============================================================================
17 // declarations
18 // ============================================================================
19
20 // ----------------------------------------------------------------------------
21 // headers
22 // ----------------------------------------------------------------------------
23
24 // for compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
26
27 #ifdef __BORLANDC__
28 #pragma hdrstop
29 #endif
30
31 #include "wx/stopwatch.h"
32
33 #ifndef WX_PRECOMP
34 #ifdef __WXMSW__
35 #include "wx/msw/wrapwin.h"
36 #endif
37 #include "wx/intl.h"
38 #include "wx/log.h"
39 #endif //WX_PRECOMP
40
41 // ----------------------------------------------------------------------------
42 // System headers
43 // ----------------------------------------------------------------------------
44
45 #if defined(__WIN32__) && !defined(HAVE_FTIME) && !defined(__MWERKS__) && !defined(__WXWINCE__)
46 #define HAVE_FTIME
47 #endif
48
49 #if defined(__VISAGECPP__) && !defined(HAVE_FTIME)
50 #define HAVE_FTIME
51 # if __IBMCPP__ >= 400
52 # define ftime(x) _ftime(x)
53 # endif
54 #endif
55
56 #if defined(__MWERKS__) && defined(__WXMSW__)
57 # undef HAVE_FTIME
58 # undef HAVE_GETTIMEOFDAY
59 #endif
60
61 #ifndef __WXPALMOS5__
62 #ifndef __WXWINCE__
63 #include <time.h>
64 #else
65 #include "wx/msw/private.h"
66 #include "wx/msw/wince/time.h"
67 #endif
68 #endif // __WXPALMOS5__
69
70
71 #if !defined(__WXMAC__) && !defined(__WXWINCE__)
72 #include <sys/types.h> // for time_t
73 #endif
74
75 #if defined(HAVE_GETTIMEOFDAY)
76 #include <sys/time.h>
77 #include <unistd.h>
78 #elif defined(HAVE_FTIME)
79 #include <sys/timeb.h>
80 #endif
81
82 #ifdef __WXPALMOS__
83 #include <DateTime.h>
84 #include <TimeMgr.h>
85 #include <SystemMgr.h>
86 #endif
87
88 // ============================================================================
89 // implementation
90 // ============================================================================
91
92 // ----------------------------------------------------------------------------
93 // wxStopWatch
94 // ----------------------------------------------------------------------------
95
96 #if wxUSE_STOPWATCH
97
98 #ifdef __WXMSW__
99
100 namespace
101 {
102
103 struct PerfCounter
104 {
105 PerfCounter()
106 {
107 init = false;
108 }
109
110 bool CanBeUsed() const
111 {
112 return freq.QuadPart != 0;
113 }
114
115 wxCriticalSection cs;
116 LARGE_INTEGER freq;
117 bool init;
118 } gs_perfCounter;
119
120 } // anonymous namespace
121
122 #endif // __WXMSW__
123
124 void wxStopWatch::Start(long t)
125 {
126 #ifdef __WXMSW__
127 if ( !gs_perfCounter.init )
128 {
129 wxCriticalSectionLocker lock(gs_perfCounter.cs);
130 ::QueryPerformanceFrequency(&gs_perfCounter.freq);
131 gs_perfCounter.init = true;
132 }
133
134 LARGE_INTEGER counter;
135 if ( gs_perfCounter.CanBeUsed() && ::QueryPerformanceCounter(&counter) )
136 {
137 m_t0 = counter.QuadPart - t*gs_perfCounter.freq.QuadPart/1000;
138 }
139 else // Fall back to the generic code below.
140 #endif // __WXMSW__
141 {
142 m_t0 = wxGetLocalTimeMillis() - t;
143 }
144
145 m_pause = 0;
146 m_pauseCount = 0;
147 }
148
149 long wxStopWatch::GetElapsedTime() const
150 {
151 #ifdef __WXMSW__
152 LARGE_INTEGER counter;
153 if ( gs_perfCounter.CanBeUsed() && ::QueryPerformanceCounter(&counter) )
154 {
155 wxLongLong delta(counter.QuadPart);
156 delta -= m_t0;
157
158 return ((delta*1000)/gs_perfCounter.freq.QuadPart).GetLo();
159 }
160 #endif
161 return (wxGetLocalTimeMillis() - m_t0).GetLo();
162 }
163
164 long wxStopWatch::Time() const
165 {
166 return m_pauseCount ? m_pause : GetElapsedTime();
167 }
168
169 #endif // wxUSE_STOPWATCH
170
171 // ----------------------------------------------------------------------------
172 // old timer functions superceded by wxStopWatch
173 // ----------------------------------------------------------------------------
174
175 #if wxUSE_LONGLONG
176
177 static wxLongLong wxStartTime = 0l;
178
179 // starts the global timer
180 void wxStartTimer()
181 {
182 wxStartTime = wxGetLocalTimeMillis();
183 }
184
185 // Returns elapsed time in milliseconds
186 long wxGetElapsedTime(bool resetTimer)
187 {
188 wxLongLong oldTime = wxStartTime;
189 wxLongLong newTime = wxGetLocalTimeMillis();
190
191 if ( resetTimer )
192 wxStartTime = newTime;
193
194 return (newTime - oldTime).GetLo();
195 }
196
197 #endif // wxUSE_LONGLONG
198
199 // ----------------------------------------------------------------------------
200 // the functions to get the current time and timezone info
201 // ----------------------------------------------------------------------------
202
203 // Get local time as seconds since 00:00:00, Jan 1st 1970
204 long wxGetLocalTime()
205 {
206 struct tm tm;
207 time_t t0, t1;
208
209 // This cannot be made static because mktime can overwrite it.
210 //
211 memset(&tm, 0, sizeof(tm));
212 tm.tm_year = 70;
213 tm.tm_mon = 0;
214 tm.tm_mday = 5; // not Jan 1st 1970 due to mktime 'feature'
215 tm.tm_hour = 0;
216 tm.tm_min = 0;
217 tm.tm_sec = 0;
218 tm.tm_isdst = -1; // let mktime guess
219
220 // Note that mktime assumes that the struct tm contains local time.
221 //
222 t1 = time(&t1); // now
223 t0 = mktime(&tm); // origin
224
225 // Return the difference in seconds.
226 //
227 if (( t0 != (time_t)-1 ) && ( t1 != (time_t)-1 ))
228 return (long)difftime(t1, t0) + (60 * 60 * 24 * 4);
229
230 wxLogSysError(_("Failed to get the local system time"));
231 return -1;
232 }
233
234 // Get UTC time as seconds since 00:00:00, Jan 1st 1970
235 long wxGetUTCTime()
236 {
237 return (long)time(NULL);
238 }
239
240 #if wxUSE_LONGLONG
241
242 // Get local time as milliseconds since 00:00:00, Jan 1st 1970
243 wxLongLong wxGetLocalTimeMillis()
244 {
245 wxLongLong val = 1000l;
246
247 // If possible, use a function which avoids conversions from
248 // broken-up time structures to milliseconds
249
250 #if defined(__WXPALMOS__)
251 DateTimeType thenst;
252 thenst.second = 0;
253 thenst.minute = 0;
254 thenst.hour = 0;
255 thenst.day = 1;
256 thenst.month = 1;
257 thenst.year = 1970;
258 thenst.weekDay = 5;
259 uint32_t now = TimGetSeconds();
260 uint32_t then = TimDateTimeToSeconds (&thenst);
261 return SysTimeToMilliSecs(SysTimeInSecs(now - then));
262 #elif defined(__WXMSW__) && (defined(__WINE__) || defined(__MWERKS__))
263 // This should probably be the way all WXMSW compilers should do it
264 // Go direct to the OS for time
265
266 SYSTEMTIME thenst = { 1970, 1, 4, 1, 0, 0, 0, 0 }; // 00:00:00 Jan 1st 1970
267 FILETIME thenft;
268 SystemTimeToFileTime( &thenst, &thenft );
269 wxLongLong then( thenft.dwHighDateTime, thenft.dwLowDateTime ); // time in 100 nanoseconds
270
271 SYSTEMTIME nowst;
272 GetLocalTime( &nowst );
273 FILETIME nowft;
274 SystemTimeToFileTime( &nowst, &nowft );
275 wxLongLong now( nowft.dwHighDateTime, nowft.dwLowDateTime ); // time in 100 nanoseconds
276
277 return ( now - then ) / 10000.0; // time from 00:00:00 Jan 1st 1970 to now in milliseconds
278
279 #elif defined(HAVE_GETTIMEOFDAY)
280 struct timeval tp;
281 if ( wxGetTimeOfDay(&tp) != -1 )
282 {
283 val *= tp.tv_sec;
284 return (val + (tp.tv_usec / 1000));
285 }
286 else
287 {
288 wxLogError(_("wxGetTimeOfDay failed."));
289 return 0;
290 }
291 #elif defined(HAVE_FTIME)
292 struct timeb tp;
293
294 // ftime() is void and not int in some mingw32 headers, so don't
295 // test the return code (well, it shouldn't fail anyhow...)
296 (void)::ftime(&tp);
297 val *= tp.time;
298 return (val + tp.millitm);
299 #else // no gettimeofday() nor ftime()
300 // We use wxGetLocalTime() to get the seconds since
301 // 00:00:00 Jan 1st 1970 and then whatever is available
302 // to get millisecond resolution.
303 //
304 // NOTE that this might lead to a problem if the clocks
305 // use different sources, so this approach should be
306 // avoided where possible.
307
308 val *= wxGetLocalTime();
309
310 // GRG: This will go soon as all WIN32 seem to have ftime
311 // JACS: unfortunately not. WinCE doesn't have it.
312 #if defined (__WIN32__)
313 // If your platform/compiler needs to use two different functions
314 // to get ms resolution, please do NOT just shut off these warnings,
315 // drop me a line instead at <guille@iies.es>
316
317 // FIXME
318 #ifndef __WXWINCE__
319 #warning "Possible clock skew bug in wxGetLocalTimeMillis()!"
320 #endif
321
322 SYSTEMTIME st;
323 ::GetLocalTime(&st);
324 val += st.wMilliseconds;
325 #else // !Win32
326 // If your platform/compiler does not support ms resolution please
327 // do NOT just shut off these warnings, drop me a line instead at
328 // <guille@iies.es>
329
330 #if defined(__VISUALC__) || defined (__WATCOMC__)
331 #pragma message("wxStopWatch will be up to second resolution!")
332 #elif defined(__BORLANDC__)
333 #pragma message "wxStopWatch will be up to second resolution!"
334 #else
335 #warning "wxStopWatch will be up to second resolution!"
336 #endif // compiler
337 #endif
338
339 return val;
340
341 #endif // time functions
342 }
343
344 #else // !wxUSE_LONGLONG
345
346 double wxGetLocalTimeMillis(void)
347 {
348 return (double(clock()) / double(CLOCKS_PER_SEC)) * 1000.0;
349 }
350
351 #endif // wxUSE_LONGLONG/!wxUSE_LONGLONG