gtimer: remove warnings about threads
[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 #ifdef HAVE_SYS_TIME_H
41 #include <sys/time.h>
42 #endif
43 #include <time.h>
44 #ifndef G_OS_WIN32
45 #include <errno.h>
46 #endif /* G_OS_WIN32 */
47
48 #ifdef G_OS_WIN32
49 #include <windows.h>
50 #endif /* G_OS_WIN32 */
51
52 #include "gtimer.h"
53
54 #include "gmem.h"
55 #include "gstrfuncs.h"
56 #include "gtestutils.h"
57 #include "gmain.h"
58
59 /**
60  * SECTION:timers
61  * @title: Timers
62  * @short_description: keep track of elapsed time
63  *
64  * #GTimer records a start time, and counts microseconds elapsed since
65  * that time. This is done somewhat differently on different platforms,
66  * and can be tricky to get exactly right, so #GTimer provides a
67  * portable/convenient interface.
68  **/
69
70 /**
71  * GTimer:
72  *
73  * Opaque datatype that records a start time.
74  **/
75 struct _GTimer
76 {
77   guint64 start;
78   guint64 end;
79
80   guint active : 1;
81 };
82
83 /**
84  * g_timer_new:
85  * @Returns: a new #GTimer.
86  *
87  * Creates a new timer, and starts timing (i.e. g_timer_start() is
88  * implicitly called for you).
89  **/
90 GTimer*
91 g_timer_new (void)
92 {
93   GTimer *timer;
94
95   timer = g_new (GTimer, 1);
96   timer->active = TRUE;
97
98   timer->start = g_get_monotonic_time ();
99
100   return timer;
101 }
102
103 /**
104  * g_timer_destroy:
105  * @timer: a #GTimer to destroy.
106  *
107  * Destroys a timer, freeing associated resources.
108  **/
109 void
110 g_timer_destroy (GTimer *timer)
111 {
112   g_return_if_fail (timer != NULL);
113
114   g_free (timer);
115 }
116
117 /**
118  * g_timer_start:
119  * @timer: a #GTimer.
120  *
121  * Marks a start time, so that future calls to g_timer_elapsed() will
122  * report the time since g_timer_start() was called. g_timer_new()
123  * automatically marks the start time, so no need to call
124  * g_timer_start() immediately after creating the timer.
125  **/
126 void
127 g_timer_start (GTimer *timer)
128 {
129   g_return_if_fail (timer != NULL);
130
131   timer->active = TRUE;
132
133   timer->start = g_get_monotonic_time ();
134 }
135
136 /**
137  * g_timer_stop:
138  * @timer: a #GTimer.
139  *
140  * Marks an end time, so calls to g_timer_elapsed() will return the
141  * difference between this end time and the start time.
142  **/
143 void
144 g_timer_stop (GTimer *timer)
145 {
146   g_return_if_fail (timer != NULL);
147
148   timer->active = FALSE;
149
150   timer->end = g_get_monotonic_time ();
151 }
152
153 /**
154  * g_timer_reset:
155  * @timer: a #GTimer.
156  *
157  * This function is useless; it's fine to call g_timer_start() on an
158  * already-started timer to reset the start time, so g_timer_reset()
159  * serves no purpose.
160  **/
161 void
162 g_timer_reset (GTimer *timer)
163 {
164   g_return_if_fail (timer != NULL);
165
166   timer->start = g_get_monotonic_time ();
167 }
168
169 /**
170  * g_timer_continue:
171  * @timer: a #GTimer.
172  *
173  * Resumes a timer that has previously been stopped with
174  * g_timer_stop(). g_timer_stop() must be called before using this
175  * function.
176  *
177  * Since: 2.4
178  **/
179 void
180 g_timer_continue (GTimer *timer)
181 {
182   guint64 elapsed;
183
184   g_return_if_fail (timer != NULL);
185   g_return_if_fail (timer->active == FALSE);
186
187   /* Get elapsed time and reset timer start time
188    *  to the current time minus the previously
189    *  elapsed interval.
190    */
191
192   elapsed = timer->end - timer->start;
193
194   timer->start = g_get_monotonic_time ();
195
196   timer->start -= elapsed;
197
198   timer->active = TRUE;
199 }
200
201 /**
202  * g_timer_elapsed:
203  * @timer: a #GTimer.
204  * @microseconds: return location for the fractional part of seconds
205  *                elapsed, in microseconds (that is, the total number
206  *                of microseconds elapsed, modulo 1000000), or %NULL
207  * @Returns: seconds elapsed as a floating point value, including any
208  *           fractional part.
209  *
210  * If @timer has been started but not stopped, obtains the time since
211  * the timer was started. If @timer has been stopped, obtains the
212  * elapsed time between the time it was started and the time it was
213  * stopped. The return value is the number of seconds elapsed,
214  * including any fractional part. The @microseconds out parameter is
215  * essentially useless.
216  **/
217 gdouble
218 g_timer_elapsed (GTimer *timer,
219                  gulong *microseconds)
220 {
221   gdouble total;
222   gint64 elapsed;
223
224   g_return_val_if_fail (timer != NULL, 0);
225
226   if (timer->active)
227     timer->end = g_get_monotonic_time ();
228
229   elapsed = timer->end - timer->start;
230
231   total = elapsed / 1e6;
232
233   if (microseconds)
234     *microseconds = elapsed % 1000000;
235
236   return total;
237 }
238
239 void
240 g_usleep (gulong microseconds)
241 {
242 #ifdef G_OS_WIN32
243   Sleep (microseconds / 1000);
244 #else
245   struct timespec request, remaining;
246   request.tv_sec = microseconds / G_USEC_PER_SEC;
247   request.tv_nsec = 1000 * (microseconds % G_USEC_PER_SEC);
248   while (nanosleep (&request, &remaining) == -1 && errno == EINTR)
249     request = remaining;
250 #endif
251 }
252
253 /**
254  * g_time_val_add:
255  * @time_: a #GTimeVal
256  * @microseconds: number of microseconds to add to @time
257  *
258  * Adds the given number of microseconds to @time_. @microseconds can
259  * also be negative to decrease the value of @time_.
260  **/
261 void 
262 g_time_val_add (GTimeVal *time_, glong microseconds)
263 {
264   g_return_if_fail (time_->tv_usec >= 0 && time_->tv_usec < G_USEC_PER_SEC);
265
266   if (microseconds >= 0)
267     {
268       time_->tv_usec += microseconds % G_USEC_PER_SEC;
269       time_->tv_sec += microseconds / G_USEC_PER_SEC;
270       if (time_->tv_usec >= G_USEC_PER_SEC)
271        {
272          time_->tv_usec -= G_USEC_PER_SEC;
273          time_->tv_sec++;
274        }
275     }
276   else
277     {
278       microseconds *= -1;
279       time_->tv_usec -= microseconds % G_USEC_PER_SEC;
280       time_->tv_sec -= microseconds / G_USEC_PER_SEC;
281       if (time_->tv_usec < 0)
282        {
283          time_->tv_usec += G_USEC_PER_SEC;
284          time_->tv_sec--;
285        }      
286     }
287 }
288
289 /* converts a broken down date representation, relative to UTC, to
290  * a timestamp; it uses timegm() if it's available.
291  */
292 static time_t
293 mktime_utc (struct tm *tm)
294 {
295   time_t retval;
296   
297 #ifndef HAVE_TIMEGM
298   static const gint days_before[] =
299   {
300     0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
301   };
302 #endif
303
304 #ifndef HAVE_TIMEGM
305   if (tm->tm_mon < 0 || tm->tm_mon > 11)
306     return (time_t) -1;
307
308   retval = (tm->tm_year - 70) * 365;
309   retval += (tm->tm_year - 68) / 4;
310   retval += days_before[tm->tm_mon] + tm->tm_mday - 1;
311   
312   if (tm->tm_year % 4 == 0 && tm->tm_mon < 2)
313     retval -= 1;
314   
315   retval = ((((retval * 24) + tm->tm_hour) * 60) + tm->tm_min) * 60 + tm->tm_sec;
316 #else
317   retval = timegm (tm);
318 #endif /* !HAVE_TIMEGM */
319   
320   return retval;
321 }
322
323 /**
324  * g_time_val_from_iso8601:
325  * @iso_date: an ISO 8601 encoded date string
326  * @time_: (out): a #GTimeVal
327  *
328  * Converts a string containing an ISO 8601 encoded date and time
329  * to a #GTimeVal and puts it into @time_.
330  *
331  * Return value: %TRUE if the conversion was successful.
332  *
333  * Since: 2.12
334  */
335 gboolean
336 g_time_val_from_iso8601 (const gchar *iso_date,
337                          GTimeVal    *time_)
338 {
339   struct tm tm = {0};
340   long val;
341
342   g_return_val_if_fail (iso_date != NULL, FALSE);
343   g_return_val_if_fail (time_ != NULL, FALSE);
344
345   /* Ensure that the first character is a digit,
346    * the first digit of the date, otherwise we don't
347    * have an ISO 8601 date */
348   while (g_ascii_isspace (*iso_date))
349     iso_date++;
350
351   if (*iso_date == '\0')
352     return FALSE;
353
354   if (!g_ascii_isdigit (*iso_date) && *iso_date != '-' && *iso_date != '+')
355     return FALSE;
356
357   val = strtoul (iso_date, (char **)&iso_date, 10);
358   if (*iso_date == '-')
359     {
360       /* YYYY-MM-DD */
361       tm.tm_year = val - 1900;
362       iso_date++;
363       tm.tm_mon = strtoul (iso_date, (char **)&iso_date, 10) - 1;
364       
365       if (*iso_date++ != '-')
366         return FALSE;
367       
368       tm.tm_mday = strtoul (iso_date, (char **)&iso_date, 10);
369     }
370   else
371     {
372       /* YYYYMMDD */
373       tm.tm_mday = val % 100;
374       tm.tm_mon = (val % 10000) / 100 - 1;
375       tm.tm_year = val / 10000 - 1900;
376     }
377
378   if (*iso_date != 'T')
379     {
380       /* Date only */
381       if (*iso_date == '\0')
382         return TRUE;
383       return FALSE;
384     }
385
386   iso_date++;
387
388   /* If there is a 'T' then there has to be a time */
389   if (!g_ascii_isdigit (*iso_date))
390     return FALSE;
391
392   val = strtoul (iso_date, (char **)&iso_date, 10);
393   if (*iso_date == ':')
394     {
395       /* hh:mm:ss */
396       tm.tm_hour = val;
397       iso_date++;
398       tm.tm_min = strtoul (iso_date, (char **)&iso_date, 10);
399       
400       if (*iso_date++ != ':')
401         return FALSE;
402       
403       tm.tm_sec = strtoul (iso_date, (char **)&iso_date, 10);
404     }
405   else
406     {
407       /* hhmmss */
408       tm.tm_sec = val % 100;
409       tm.tm_min = (val % 10000) / 100;
410       tm.tm_hour = val / 10000;
411     }
412
413   time_->tv_usec = 0;
414   
415   if (*iso_date == ',' || *iso_date == '.')
416     {
417       glong mul = 100000;
418
419       while (g_ascii_isdigit (*++iso_date))
420         {
421           time_->tv_usec += (*iso_date - '0') * mul;
422           mul /= 10;
423         }
424     }
425     
426   /* Now parse the offset and convert tm to a time_t */
427   if (*iso_date == 'Z')
428     {
429       iso_date++;
430       time_->tv_sec = mktime_utc (&tm);
431     }
432   else if (*iso_date == '+' || *iso_date == '-')
433     {
434       gint sign = (*iso_date == '+') ? -1 : 1;
435       
436       val = strtoul (iso_date + 1, (char **)&iso_date, 10);
437       
438       if (*iso_date == ':')
439         val = 60 * val + strtoul (iso_date + 1, (char **)&iso_date, 10);
440       else
441         val = 60 * (val / 100) + (val % 100);
442
443       time_->tv_sec = mktime_utc (&tm) + (time_t) (60 * val * sign);
444     }
445   else
446     {
447       /* No "Z" or offset, so local time */
448       tm.tm_isdst = -1; /* locale selects DST */
449       time_->tv_sec = mktime (&tm);
450     }
451
452   while (g_ascii_isspace (*iso_date))
453     iso_date++;
454
455   return *iso_date == '\0';
456 }
457
458 /**
459  * g_time_val_to_iso8601:
460  * @time_: a #GTimeVal
461  * 
462  * Converts @time_ into an ISO 8601 encoded string, relative to the
463  * Coordinated Universal Time (UTC).
464  *
465  * Return value: a newly allocated string containing an ISO 8601 date
466  *
467  * Since: 2.12
468  */
469 gchar *
470 g_time_val_to_iso8601 (GTimeVal *time_)
471 {
472   gchar *retval;
473   struct tm *tm;
474 #ifdef HAVE_GMTIME_R
475   struct tm tm_;
476 #endif
477   time_t secs;
478   
479   g_return_val_if_fail (time_->tv_usec >= 0 && time_->tv_usec < G_USEC_PER_SEC, NULL);
480
481  secs = time_->tv_sec;
482 #ifdef _WIN32
483  tm = gmtime (&secs);
484 #else
485 #ifdef HAVE_GMTIME_R
486   tm = gmtime_r (&secs, &tm_);
487 #else
488   tm = gmtime (&secs);
489 #endif
490 #endif
491
492   if (time_->tv_usec != 0)
493     {
494       /* ISO 8601 date and time format, with fractionary seconds:
495        *   YYYY-MM-DDTHH:MM:SS.MMMMMMZ
496        */
497       retval = g_strdup_printf ("%4d-%02d-%02dT%02d:%02d:%02d.%06ldZ",
498                                 tm->tm_year + 1900,
499                                 tm->tm_mon + 1,
500                                 tm->tm_mday,
501                                 tm->tm_hour,
502                                 tm->tm_min,
503                                 tm->tm_sec,
504                                 time_->tv_usec);
505     }
506   else
507     {
508       /* ISO 8601 date and time format:
509        *   YYYY-MM-DDTHH:MM:SSZ
510        */
511       retval = g_strdup_printf ("%4d-%02d-%02dT%02d:%02d:%02dZ",
512                                 tm->tm_year + 1900,
513                                 tm->tm_mon + 1,
514                                 tm->tm_mday,
515                                 tm->tm_hour,
516                                 tm->tm_min,
517                                 tm->tm_sec);
518     }
519   
520   return retval;
521 }