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