Bug 527214 – g_timer_elapsed() returns random values.
[platform/upstream/glib.git] / glib / gtimer.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GLib Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
25  */
26
27 /* 
28  * MT safe
29  */
30
31 #include "config.h"
32 #include "glibconfig.h"
33
34 #include <stdlib.h>
35
36 #ifdef HAVE_UNISTD_H
37 #include <unistd.h>
38 #endif /* HAVE_UNISTD_H */
39
40 #ifndef G_OS_WIN32
41 #include <sys/time.h>
42 #include <time.h>
43 #include <errno.h>
44 #endif /* G_OS_WIN32 */
45
46 #ifdef G_OS_WIN32
47 #include <windows.h>
48 #endif /* G_OS_WIN32 */
49
50 #include "glib.h"
51 #include "gthread.h"
52 #include "galias.h"
53
54 #define G_NSEC_PER_SEC 1000000000
55
56 #define GETTIME(v) (v = g_thread_gettime ())
57
58 struct _GTimer
59 {
60   guint64 start;
61   guint64 end;
62
63   guint active : 1;
64 };
65
66
67 GTimer*
68 g_timer_new (void)
69 {
70   GTimer *timer;
71
72   if (!g_thread_supported ())
73     g_warning ("g_timer_new() called, but GThreads not initialized yet. "
74                "Call g_thread_init ().");
75
76   timer = g_new (GTimer, 1);
77   timer->active = TRUE;
78
79   GETTIME (timer->start);
80
81   return timer;
82 }
83
84 void
85 g_timer_destroy (GTimer *timer)
86 {
87   g_return_if_fail (timer != NULL);
88
89   g_free (timer);
90 }
91
92 void
93 g_timer_start (GTimer *timer)
94 {
95   g_return_if_fail (timer != NULL);
96
97   timer->active = TRUE;
98
99   GETTIME (timer->start);
100 }
101
102 void
103 g_timer_stop (GTimer *timer)
104 {
105   g_return_if_fail (timer != NULL);
106
107   timer->active = FALSE;
108
109   GETTIME (timer->end);
110 }
111
112 void
113 g_timer_reset (GTimer *timer)
114 {
115   g_return_if_fail (timer != NULL);
116
117   GETTIME (timer->start);
118 }
119
120 void
121 g_timer_continue (GTimer *timer)
122 {
123   guint64 elapsed;
124
125   g_return_if_fail (timer != NULL);
126   g_return_if_fail (timer->active == FALSE);
127
128   /* Get elapsed time and reset timer start time
129    *  to the current time minus the previously
130    *  elapsed interval.
131    */
132
133   elapsed = timer->end - timer->start;
134
135   GETTIME (timer->start);
136
137   timer->start -= elapsed;
138
139   timer->active = TRUE;
140 }
141
142 gdouble
143 g_timer_elapsed (GTimer *timer,
144                  gulong *microseconds)
145 {
146   gdouble total;
147   gint64 elapsed;
148
149   g_return_val_if_fail (timer != NULL, 0);
150
151   if (timer->active)
152     GETTIME (timer->end);
153
154   elapsed = timer->end - timer->start;
155
156   total = elapsed / 1e9;
157
158   if (microseconds)
159     *microseconds = (elapsed / 1000) % 1000000;
160
161   return total;
162 }
163
164 void
165 g_usleep (gulong microseconds)
166 {
167 #ifdef G_OS_WIN32
168   Sleep (microseconds / 1000);
169 #else /* !G_OS_WIN32 */
170 # ifdef HAVE_NANOSLEEP
171   struct timespec request, remaining;
172   request.tv_sec = microseconds / G_USEC_PER_SEC;
173   request.tv_nsec = 1000 * (microseconds % G_USEC_PER_SEC);
174   while (nanosleep (&request, &remaining) == -1 && errno == EINTR)
175     request = remaining;
176 # else /* !HAVE_NANOSLEEP */
177 #  ifdef HAVE_NSLEEP
178   /* on AIX, nsleep is analogous to nanosleep */
179   struct timespec request, remaining;
180   request.tv_sec = microseconds / G_USEC_PER_SEC;
181   request.tv_nsec = 1000 * (microseconds % G_USEC_PER_SEC);
182   while (nsleep (&request, &remaining) == -1 && errno == EINTR)
183     request = remaining;
184 #  else /* !HAVE_NSLEEP */
185   if (g_thread_supported ())
186     {
187       static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
188       static GCond* cond = NULL;
189       GTimeVal end_time;
190       
191       g_get_current_time (&end_time);
192       if (microseconds > G_MAXLONG)
193         {
194           microseconds -= G_MAXLONG;
195           g_time_val_add (&end_time, G_MAXLONG);
196         }
197       g_time_val_add (&end_time, microseconds);
198
199       g_static_mutex_lock (&mutex);
200       
201       if (!cond)
202         cond = g_cond_new ();
203       
204       while (g_cond_timed_wait (cond, g_static_mutex_get_mutex (&mutex), 
205                                 &end_time))
206         /* do nothing */;
207       
208       g_static_mutex_unlock (&mutex);
209     }
210   else
211     {
212       struct timeval tv;
213       tv.tv_sec = microseconds / G_USEC_PER_SEC;
214       tv.tv_usec = microseconds % G_USEC_PER_SEC;
215       select(0, NULL, NULL, NULL, &tv);
216     }
217 #  endif /* !HAVE_NSLEEP */
218 # endif /* !HAVE_NANOSLEEP */
219 #endif /* !G_OS_WIN32 */
220 }
221
222 /**
223  * g_time_val_add:
224  * @time_: a #GTimeVal
225  * @microseconds: number of microseconds to add to @time
226  *
227  * Adds the given number of microseconds to @time_. @microseconds can
228  * also be negative to decrease the value of @time_.
229  **/
230 void 
231 g_time_val_add (GTimeVal *time_, glong microseconds)
232 {
233   g_return_if_fail (time_->tv_usec >= 0 && time_->tv_usec < G_USEC_PER_SEC);
234
235   if (microseconds >= 0)
236     {
237       time_->tv_usec += microseconds % G_USEC_PER_SEC;
238       time_->tv_sec += microseconds / G_USEC_PER_SEC;
239       if (time_->tv_usec >= G_USEC_PER_SEC)
240        {
241          time_->tv_usec -= G_USEC_PER_SEC;
242          time_->tv_sec++;
243        }
244     }
245   else
246     {
247       microseconds *= -1;
248       time_->tv_usec -= microseconds % G_USEC_PER_SEC;
249       time_->tv_sec -= microseconds / G_USEC_PER_SEC;
250       if (time_->tv_usec < 0)
251        {
252          time_->tv_usec += G_USEC_PER_SEC;
253          time_->tv_sec--;
254        }      
255     }
256 }
257
258 /* converts a broken down date representation, relative to UTC, to
259  * a timestamp; it uses timegm() if it's available.
260  */
261 static time_t
262 mktime_utc (struct tm *tm)
263 {
264   time_t retval;
265   
266 #ifndef HAVE_TIMEGM
267   static const gint days_before[] =
268   {
269     0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
270   };
271 #endif
272
273 #ifndef HAVE_TIMEGM
274   if (tm->tm_mon < 0 || tm->tm_mon > 11)
275     return (time_t) -1;
276
277   retval = (tm->tm_year - 70) * 365;
278   retval += (tm->tm_year - 68) / 4;
279   retval += days_before[tm->tm_mon] + tm->tm_mday - 1;
280   
281   if (tm->tm_year % 4 == 0 && tm->tm_mon < 2)
282     retval -= 1;
283   
284   retval = ((((retval * 24) + tm->tm_hour) * 60) + tm->tm_min) * 60 + tm->tm_sec;
285 #else
286   retval = timegm (tm);
287 #endif /* !HAVE_TIMEGM */
288   
289   return retval;
290 }
291
292 /**
293  * g_time_val_from_iso8601:
294  * @iso_date: a ISO 8601 encoded date string
295  * @time_: a #GTimeVal
296  *
297  * Converts a string containing an ISO 8601 encoded date and time
298  * to a #GTimeVal and puts it into @time_.
299  *
300  * Return value: %TRUE if the conversion was successful.
301  *
302  * Since: 2.12
303  */
304 gboolean
305 g_time_val_from_iso8601 (const gchar *iso_date,
306                          GTimeVal    *time_)
307 {
308   struct tm tm;
309   long val;
310
311   g_return_val_if_fail (iso_date != NULL, FALSE);
312   g_return_val_if_fail (time_ != NULL, FALSE);
313
314   /* Ensure that the first character is a digit,
315    * the first digit of the date, otherwise we don't
316    * have an ISO 8601 date */
317   while (g_ascii_isspace (*iso_date))
318     iso_date++;
319
320   if (*iso_date == '\0')
321     return FALSE;
322
323   if (!g_ascii_isdigit (*iso_date) && *iso_date != '-' && *iso_date != '+')
324     return FALSE;
325
326   val = strtoul (iso_date, (char **)&iso_date, 10);
327   if (*iso_date == '-')
328     {
329       /* YYYY-MM-DD */
330       tm.tm_year = val - 1900;
331       iso_date++;
332       tm.tm_mon = strtoul (iso_date, (char **)&iso_date, 10) - 1;
333       
334       if (*iso_date++ != '-')
335         return FALSE;
336       
337       tm.tm_mday = strtoul (iso_date, (char **)&iso_date, 10);
338     }
339   else
340     {
341       /* YYYYMMDD */
342       tm.tm_mday = val % 100;
343       tm.tm_mon = (val % 10000) / 100 - 1;
344       tm.tm_year = val / 10000 - 1900;
345     }
346
347   if (*iso_date++ != 'T')
348     return FALSE;
349   
350   val = strtoul (iso_date, (char **)&iso_date, 10);
351   if (*iso_date == ':')
352     {
353       /* hh:mm:ss */
354       tm.tm_hour = val;
355       iso_date++;
356       tm.tm_min = strtoul (iso_date, (char **)&iso_date, 10);
357       
358       if (*iso_date++ != ':')
359         return FALSE;
360       
361       tm.tm_sec = strtoul (iso_date, (char **)&iso_date, 10);
362     }
363   else
364     {
365       /* hhmmss */
366       tm.tm_sec = val % 100;
367       tm.tm_min = (val % 10000) / 100;
368       tm.tm_hour = val / 10000;
369     }
370
371   time_->tv_sec = mktime_utc (&tm);
372   time_->tv_usec = 1;
373   
374   if (*iso_date == '.')
375     time_->tv_usec = strtoul (iso_date + 1, (char **)&iso_date, 10);
376     
377   if (*iso_date == '+' || *iso_date == '-')
378     {
379       gint sign = (*iso_date == '+') ? -1 : 1;
380       
381       val = 60 * strtoul (iso_date + 1, (char **)&iso_date, 10);
382       
383       if (*iso_date == ':')
384         val = 60 * val + strtoul (iso_date + 1, NULL, 10);
385       else
386         val = 60 * (val / 100) + (val % 100);
387
388       time_->tv_sec += (time_t) (val * sign);
389     }
390
391   return TRUE;
392 }
393
394 /**
395  * g_time_val_to_iso8601:
396  * @time_: a #GTimeVal
397  * 
398  * Converts @time_ into a ISO 8601 encoded string, relative to the
399  * Coordinated Universal Time (UTC).
400  *
401  * Return value: a newly allocated string containing a ISO 8601 date
402  *
403  * Since: 2.12
404  */
405 gchar *
406 g_time_val_to_iso8601 (GTimeVal *time_)
407 {
408   gchar *retval;
409 #ifdef HAVE_GMTIME_R
410   struct tm tm_;
411 #endif
412   
413   g_return_val_if_fail (time_->tv_usec >= 0 && time_->tv_usec < G_USEC_PER_SEC, NULL);
414
415 #define ISO_8601_LEN    21
416 #define ISO_8601_FORMAT "%Y-%m-%dT%H:%M:%SZ"
417   retval = g_new0 (gchar, ISO_8601_LEN + 1);
418
419   strftime (retval, ISO_8601_LEN,
420             ISO_8601_FORMAT,
421 #ifdef HAVE_GMTIME_R
422             gmtime_r (&(time_->tv_sec), &tm_)
423 #else
424             gmtime (&(time_->tv_sec))
425 #endif
426             );
427   
428   return retval;
429 }
430
431 #define __G_TIMER_C__
432 #include "galiasdef.c"