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