1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/time.cpp
3 // Purpose: Implementation of time-related functions.
4 // Author: Vadim Zeitlin
5 // Created: 2011-11-26
6 // Copyright: (c) 2011 Vadim Zeitlin <vadim@wxwidgets.org>
7 // Licence: wxWindows licence
8 ///////////////////////////////////////////////////////////////////////////////
9
10 // ============================================================================
11 // declarations
12 // ============================================================================
13
14 // ----------------------------------------------------------------------------
15 // headers
16 // ----------------------------------------------------------------------------
17
18 // for compilers that support precompilation, includes "wx.h".
19 #include "wx/wxprec.h"
20
21
22 #include "wx/time.h"
23
24 #ifndef WX_PRECOMP
25 #ifdef __WINDOWS__
26 #include "wx/msw/wrapwin.h"
27 #endif
28 #include "wx/intl.h"
29 #include "wx/log.h"
30 #endif
31
32 #ifndef WX_GMTOFF_IN_TM
33 // Define it for some systems which don't (always) use configure but are
34 // known to have tm_gmtoff field.
35 #if defined(__DARWIN__)
36 #define WX_GMTOFF_IN_TM
37 #endif
38 #endif
39
40 #include <time.h>
41
42 wxDECL_FOR_STRICT_MINGW32(void, tzset, (void));
43
44 #if !defined(__WXMAC__)
45 #include <sys/types.h> // for time_t
46 #endif
47
48 #if defined(HAVE_GETTIMEOFDAY)
49 #include <sys/time.h>
50 #include <unistd.h>
51 #elif defined(HAVE_FTIME)
52 #include <sys/timeb.h>
53 #endif
54
55 #if defined(__WINE__)
56 #include <sys/timeb.h>
57 #include <values.h>
58 #endif
59
60 namespace
61 {
62
63 const int MILLISECONDS_PER_SECOND = 1000;
64 #if !defined(__WINDOWS__)
65 const int MICROSECONDS_PER_MILLISECOND = 1000;
66 #ifdef HAVE_GETTIMEOFDAY
67 const int MICROSECONDS_PER_SECOND = 1000*1000;
68 #endif
69 #endif
70
71 } // anonymous namespace
72
73 // ============================================================================
74 // implementation
75 // ============================================================================
76
77 #if (!defined(HAVE_LOCALTIME_R) || !defined(HAVE_GMTIME_R)) && wxUSE_THREADS && !defined(__WINDOWS__)
78 static wxMutex timeLock;
79 #endif
80
81 #ifndef HAVE_LOCALTIME_R
wxLocaltime_r(const time_t * ticks,struct tm * temp)82 struct tm *wxLocaltime_r(const time_t* ticks, struct tm* temp)
83 {
84 #if wxUSE_THREADS && !defined(__WINDOWS__)
85 // No need to waste time with a mutex on windows since it's using
86 // thread local storage for localtime anyway.
87 wxMutexLocker locker(timeLock);
88 #endif
89
90 const tm * const t = localtime(ticks);
91 if ( !t )
92 return NULL;
93
94 memcpy(temp, t, sizeof(struct tm));
95 return temp;
96 }
97 #endif // !HAVE_LOCALTIME_R
98
99 #ifndef HAVE_GMTIME_R
wxGmtime_r(const time_t * ticks,struct tm * temp)100 struct tm *wxGmtime_r(const time_t* ticks, struct tm* temp)
101 {
102 #if wxUSE_THREADS && !defined(__WINDOWS__)
103 // No need to waste time with a mutex on windows since it's
104 // using thread local storage for gmtime anyway.
105 wxMutexLocker locker(timeLock);
106 #endif
107
108 const tm * const t = gmtime(ticks);
109 if ( !t )
110 return NULL;
111
112 memcpy(temp, gmtime(ticks), sizeof(struct tm));
113 return temp;
114 }
115 #endif // !HAVE_GMTIME_R
116
117 // returns the time zone in the C sense, i.e. the difference UTC - local
118 // (in seconds)
wxGetTimeZone()119 int wxGetTimeZone()
120 {
121 #ifdef WX_GMTOFF_IN_TM
122 // set to true when the timezone is set
123 static bool s_timezoneSet = false;
124 static long gmtoffset = LONG_MAX; // invalid timezone
125
126 // ensure that the timezone variable is set by calling wxLocaltime_r
127 if ( !s_timezoneSet )
128 {
129 // just call wxLocaltime_r() instead of figuring out whether this
130 // system supports tzset(), _tzset() or something else
131 time_t t = time(NULL);
132 struct tm tm;
133
134 wxLocaltime_r(&t, &tm);
135 s_timezoneSet = true;
136
137 // note that GMT offset is the opposite of time zone and so to return
138 // consistent results in both WX_GMTOFF_IN_TM and !WX_GMTOFF_IN_TM
139 // cases we have to negate it
140 gmtoffset = -tm.tm_gmtoff;
141
142 // this function is supposed to return the same value whether DST is
143 // enabled or not, so we need to use an additional offset if DST is on
144 // as tm_gmtoff already does include it
145 if ( tm.tm_isdst )
146 gmtoffset += 3600;
147 }
148 return (int)gmtoffset;
149 #elif defined(__WINE__)
150 struct timeb tb;
151 ftime(&tb);
152 return tb.timezone*60;
153 #elif defined(__VISUALC__)
154 // We must initialize the time zone information before using it. It's not a
155 // problem if we do it twice due to a race condition, as it's idempotent
156 // anyhow, so don't bother with any locks here.
157 static bool s_tzSet = (_tzset(), true);
158 wxUnusedVar(s_tzSet);
159
160 // Starting with VC++ 8 timezone variable is deprecated and is not even
161 // available in some standard library version so use the new function for
162 // accessing it instead.
163 #if wxCHECK_VISUALC_VERSION(8)
164 long t;
165 _get_timezone(&t);
166 return t;
167 #else // VC++ < 8
168 return timezone;
169 #endif
170 #else // Use some kind of time zone variable.
171 // In any case we must initialize the time zone before using it.
172 static bool s_tzSet = (tzset(), true);
173 wxUnusedVar(s_tzSet);
174
175 #if defined(WX_TIMEZONE) // If WX_TIMEZONE was defined by configure, use it.
176 return WX_TIMEZONE;
177 #elif defined(__MINGW32__)
178 #if defined(__MINGW32_TOOLCHAIN__) && defined(__STRICT_ANSI__)
179 extern long _timezone;
180 #endif
181
182 return _timezone;
183 #else // unknown platform -- assume it has timezone
184 return timezone;
185 #endif // different time zone variables
186 #endif // different ways to determine time zone
187 }
188
189 // Get local time as seconds since 00:00:00, Jan 1st 1970
wxGetLocalTime()190 long wxGetLocalTime()
191 {
192 struct tm tm;
193 time_t t0, t1;
194
195 // This cannot be made static because mktime can overwrite it.
196 //
197 memset(&tm, 0, sizeof(tm));
198 tm.tm_year = 70;
199 tm.tm_mon = 0;
200 tm.tm_mday = 5; // not Jan 1st 1970 due to mktime 'feature'
201 tm.tm_hour = 0;
202 tm.tm_min = 0;
203 tm.tm_sec = 0;
204 tm.tm_isdst = -1; // let mktime guess
205
206 // Note that mktime assumes that the struct tm contains local time.
207 //
208 t1 = time(&t1); // now
209 t0 = mktime(&tm); // origin
210
211 // Return the difference in seconds.
212 //
213 if (( t0 != (time_t)-1 ) && ( t1 != (time_t)-1 ))
214 return (long)difftime(t1, t0) + (60 * 60 * 24 * 4);
215
216 wxLogSysError(_("Failed to get the local system time"));
217 return -1;
218 }
219
220 // Get UTC time as seconds since 00:00:00, Jan 1st 1970
wxGetUTCTime()221 long wxGetUTCTime()
222 {
223 return (long)time(NULL);
224 }
225
226 #if wxUSE_LONGLONG
227
wxGetUTCTimeUSec()228 wxLongLong wxGetUTCTimeUSec()
229 {
230 #if defined(__WINDOWS__)
231 FILETIME ft;
232 ::GetSystemTimeAsFileTime(&ft);
233
234 // FILETIME is in 100ns or 0.1us since 1601-01-01, transform to us since
235 // 1970-01-01.
236 wxLongLong t(ft.dwHighDateTime, ft.dwLowDateTime);
237 t /= 10;
238 t -= wxLL(11644473600000000); // Unix - Windows epochs difference in us.
239 return t;
240 #else // non-MSW
241
242 #ifdef HAVE_GETTIMEOFDAY
243 timeval tv;
244 if ( wxGetTimeOfDay(&tv) != -1 )
245 {
246 wxLongLong val(tv.tv_sec);
247 val *= MICROSECONDS_PER_SECOND;
248 val += tv.tv_usec;
249 return val;
250 }
251 #endif // HAVE_GETTIMEOFDAY
252
253 // Fall back to lesser precision function.
254 return wxGetUTCTimeMillis()*MICROSECONDS_PER_MILLISECOND;
255 #endif // MSW/!MSW
256 }
257
258 // Get local time as milliseconds since 00:00:00, Jan 1st 1970
wxGetUTCTimeMillis()259 wxLongLong wxGetUTCTimeMillis()
260 {
261 // If possible, use a function which avoids conversions from
262 // broken-up time structures to milliseconds
263 #if defined(__WINDOWS__)
264 FILETIME ft;
265 ::GetSystemTimeAsFileTime(&ft);
266
267 // FILETIME is expressed in 100ns (or 0.1us) units since 1601-01-01,
268 // transform them to ms since 1970-01-01.
269 wxLongLong t(ft.dwHighDateTime, ft.dwLowDateTime);
270 t /= 10000;
271 t -= wxLL(11644473600000); // Unix - Windows epochs difference in ms.
272 return t;
273 #else // !__WINDOWS__
274 wxLongLong val = MILLISECONDS_PER_SECOND;
275
276 #if defined(HAVE_GETTIMEOFDAY)
277 struct timeval tp;
278 if ( wxGetTimeOfDay(&tp) != -1 )
279 {
280 val *= tp.tv_sec;
281 return (val + (tp.tv_usec / MICROSECONDS_PER_MILLISECOND));
282 }
283 else
284 {
285 wxLogError(_("wxGetTimeOfDay failed."));
286 return 0;
287 }
288 #elif defined(HAVE_FTIME)
289 struct timeb tp;
290
291 // ftime() is void and not int in some mingw32 headers, so don't
292 // test the return code (well, it shouldn't fail anyhow...)
293 (void)::ftime(&tp);
294 val *= tp.time;
295 return (val + tp.millitm);
296 #else // no gettimeofday() nor ftime()
297 // If your platform/compiler does not support ms resolution please
298 // do NOT just shut off these warnings, drop me a line instead at
299 // <guille@iies.es>
300
301 #if defined(__VISUALC__)
302 #pragma message("wxStopWatch will be up to second resolution!")
303 #else
304 #warning "wxStopWatch will be up to second resolution!"
305 #endif // compiler
306
307 val *= wxGetUTCTime();
308 return val;
309 #endif // time functions
310
311 #endif // __WINDOWS__/!__WINDOWS__
312 }
313
wxGetLocalTimeMillis()314 wxLongLong wxGetLocalTimeMillis()
315 {
316 return wxGetUTCTimeMillis() - wxGetTimeZone()*MILLISECONDS_PER_SECOND;
317 }
318
319 #else // !wxUSE_LONGLONG
320
wxGetLocalTimeMillis()321 double wxGetLocalTimeMillis()
322 {
323 return (double(clock()) / double(CLOCKS_PER_SEC)) * MILLISECONDS_PER_SECOND;
324 }
325
326 #endif // wxUSE_LONGLONG/!wxUSE_LONGLONG
327