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