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