]> git.saurik.com Git - wxWidgets.git/blob - src/common/stopwatch.cpp
4ff9b7532d648b86a854c360ed46aa1a26e8479b
[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 namespace
99 {
100
101 #ifdef __WXMSW__
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 #endif // __WXMSW__
121
122 const int MILLISECONDS_PER_SECOND = 1000;
123 const int MICROSECONDS_PER_SECOND = 1000*1000;
124
125 } // anonymous namespace
126
127 void wxStopWatch::DoStart()
128 {
129 #ifdef __WXMSW__
130 if ( !gs_perfCounter.init )
131 {
132 wxCriticalSectionLocker lock(gs_perfCounter.cs);
133 ::QueryPerformanceFrequency(&gs_perfCounter.freq);
134
135 // Just a sanity check: it's not supposed to happen but verify that
136 // ::QueryPerformanceCounter() succeeds so that we can really use it.
137 LARGE_INTEGER counter;
138 if ( !::QueryPerformanceCounter(&counter) )
139 {
140 wxLogDebug("QueryPerformanceCounter() unexpected failed (%s), "
141 "will not use it.", wxSysErrorMsg());
142
143 gs_perfCounter.freq.QuadPart = 0;
144 }
145
146 gs_perfCounter.init = true;
147 }
148 #endif // __WXMSW__
149
150 m_t0 = GetCurrentClockValue();
151 }
152
153 wxLongLong wxStopWatch::GetClockFreq() const
154 {
155 #ifdef __WXMSW__
156 // Under MSW we use the high resolution performance counter timer which has
157 // its own frequency (usually related to the CPU clock speed).
158 if ( gs_perfCounter.CanBeUsed() )
159 return gs_perfCounter.freq.QuadPart;
160 #endif // __WXMSW__
161
162 // Currently milliseconds are used everywhere else.
163 return MILLISECONDS_PER_SECOND;
164 }
165
166 void wxStopWatch::Start(long t0)
167 {
168 DoStart();
169
170 m_t0 -= (wxLongLong(t0)*GetClockFreq())/MILLISECONDS_PER_SECOND;
171 }
172
173 wxLongLong wxStopWatch::GetCurrentClockValue() const
174 {
175 #ifdef __WXMSW__
176 if ( gs_perfCounter.CanBeUsed() )
177 {
178 LARGE_INTEGER counter;
179 ::QueryPerformanceCounter(&counter);
180 return counter.QuadPart;
181 }
182 #endif // __WXMSW__
183
184 return wxGetLocalTimeMillis();
185 }
186
187 wxLongLong wxStopWatch::TimeInMicro() const
188 {
189 const wxLongLong elapsed(m_pauseCount ? m_elapsedBeforePause
190 : GetCurrentClockValue() - m_t0);
191
192 return (elapsed*MICROSECONDS_PER_SECOND)/GetClockFreq();
193 }
194
195 #endif // wxUSE_STOPWATCH
196
197 // ----------------------------------------------------------------------------
198 // old timer functions superceded by wxStopWatch
199 // ----------------------------------------------------------------------------
200
201 #if wxUSE_LONGLONG
202
203 static wxLongLong wxStartTime = 0l;
204
205 // starts the global timer
206 void wxStartTimer()
207 {
208 wxStartTime = wxGetLocalTimeMillis();
209 }
210
211 // Returns elapsed time in milliseconds
212 long wxGetElapsedTime(bool resetTimer)
213 {
214 wxLongLong oldTime = wxStartTime;
215 wxLongLong newTime = wxGetLocalTimeMillis();
216
217 if ( resetTimer )
218 wxStartTime = newTime;
219
220 return (newTime - oldTime).GetLo();
221 }
222
223 #endif // wxUSE_LONGLONG
224
225 // ----------------------------------------------------------------------------
226 // the functions to get the current time and timezone info
227 // ----------------------------------------------------------------------------
228
229 // Get local time as seconds since 00:00:00, Jan 1st 1970
230 long wxGetLocalTime()
231 {
232 struct tm tm;
233 time_t t0, t1;
234
235 // This cannot be made static because mktime can overwrite it.
236 //
237 memset(&tm, 0, sizeof(tm));
238 tm.tm_year = 70;
239 tm.tm_mon = 0;
240 tm.tm_mday = 5; // not Jan 1st 1970 due to mktime 'feature'
241 tm.tm_hour = 0;
242 tm.tm_min = 0;
243 tm.tm_sec = 0;
244 tm.tm_isdst = -1; // let mktime guess
245
246 // Note that mktime assumes that the struct tm contains local time.
247 //
248 t1 = time(&t1); // now
249 t0 = mktime(&tm); // origin
250
251 // Return the difference in seconds.
252 //
253 if (( t0 != (time_t)-1 ) && ( t1 != (time_t)-1 ))
254 return (long)difftime(t1, t0) + (60 * 60 * 24 * 4);
255
256 wxLogSysError(_("Failed to get the local system time"));
257 return -1;
258 }
259
260 // Get UTC time as seconds since 00:00:00, Jan 1st 1970
261 long wxGetUTCTime()
262 {
263 return (long)time(NULL);
264 }
265
266 #if wxUSE_LONGLONG
267
268 // Get local time as milliseconds since 00:00:00, Jan 1st 1970
269 wxLongLong wxGetLocalTimeMillis()
270 {
271 wxLongLong val = 1000l;
272
273 // If possible, use a function which avoids conversions from
274 // broken-up time structures to milliseconds
275
276 #if defined(__WXPALMOS__)
277 DateTimeType thenst;
278 thenst.second = 0;
279 thenst.minute = 0;
280 thenst.hour = 0;
281 thenst.day = 1;
282 thenst.month = 1;
283 thenst.year = 1970;
284 thenst.weekDay = 5;
285 uint32_t now = TimGetSeconds();
286 uint32_t then = TimDateTimeToSeconds (&thenst);
287 return SysTimeToMilliSecs(SysTimeInSecs(now - then));
288 #elif defined(__WXMSW__) && (defined(__WINE__) || defined(__MWERKS__))
289 // This should probably be the way all WXMSW compilers should do it
290 // Go direct to the OS for time
291
292 SYSTEMTIME thenst = { 1970, 1, 4, 1, 0, 0, 0, 0 }; // 00:00:00 Jan 1st 1970
293 FILETIME thenft;
294 SystemTimeToFileTime( &thenst, &thenft );
295 wxLongLong then( thenft.dwHighDateTime, thenft.dwLowDateTime ); // time in 100 nanoseconds
296
297 SYSTEMTIME nowst;
298 GetLocalTime( &nowst );
299 FILETIME nowft;
300 SystemTimeToFileTime( &nowst, &nowft );
301 wxLongLong now( nowft.dwHighDateTime, nowft.dwLowDateTime ); // time in 100 nanoseconds
302
303 return ( now - then ) / 10000.0; // time from 00:00:00 Jan 1st 1970 to now in milliseconds
304
305 #elif defined(HAVE_GETTIMEOFDAY)
306 struct timeval tp;
307 if ( wxGetTimeOfDay(&tp) != -1 )
308 {
309 val *= tp.tv_sec;
310 return (val + (tp.tv_usec / 1000));
311 }
312 else
313 {
314 wxLogError(_("wxGetTimeOfDay failed."));
315 return 0;
316 }
317 #elif defined(HAVE_FTIME)
318 struct timeb tp;
319
320 // ftime() is void and not int in some mingw32 headers, so don't
321 // test the return code (well, it shouldn't fail anyhow...)
322 (void)::ftime(&tp);
323 val *= tp.time;
324 return (val + tp.millitm);
325 #else // no gettimeofday() nor ftime()
326 // We use wxGetLocalTime() to get the seconds since
327 // 00:00:00 Jan 1st 1970 and then whatever is available
328 // to get millisecond resolution.
329 //
330 // NOTE that this might lead to a problem if the clocks
331 // use different sources, so this approach should be
332 // avoided where possible.
333
334 val *= wxGetLocalTime();
335
336 // GRG: This will go soon as all WIN32 seem to have ftime
337 // JACS: unfortunately not. WinCE doesn't have it.
338 #if defined (__WIN32__)
339 // If your platform/compiler needs to use two different functions
340 // to get ms resolution, please do NOT just shut off these warnings,
341 // drop me a line instead at <guille@iies.es>
342
343 // FIXME
344 #ifndef __WXWINCE__
345 #warning "Possible clock skew bug in wxGetLocalTimeMillis()!"
346 #endif
347
348 SYSTEMTIME st;
349 ::GetLocalTime(&st);
350 val += st.wMilliseconds;
351 #else // !Win32
352 // If your platform/compiler does not support ms resolution please
353 // do NOT just shut off these warnings, drop me a line instead at
354 // <guille@iies.es>
355
356 #if defined(__VISUALC__) || defined (__WATCOMC__)
357 #pragma message("wxStopWatch will be up to second resolution!")
358 #elif defined(__BORLANDC__)
359 #pragma message "wxStopWatch will be up to second resolution!"
360 #else
361 #warning "wxStopWatch will be up to second resolution!"
362 #endif // compiler
363 #endif
364
365 return val;
366
367 #endif // time functions
368 }
369
370 #else // !wxUSE_LONGLONG
371
372 double wxGetLocalTimeMillis(void)
373 {
374 return (double(clock()) / double(CLOCKS_PER_SEC)) * 1000.0;
375 }
376
377 #endif // wxUSE_LONGLONG/!wxUSE_LONGLONG