Imported Upstream version 2.74.3
[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  * SPDX-License-Identifier: LGPL-2.1-or-later
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
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 G_OS_UNIX
37 #include <unistd.h>
38 #endif /* G_OS_UNIX */
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_timer_is_active:
243  * @timer: a #GTimer.
244  * 
245  * Exposes whether the timer is currently active.
246  *
247  * Returns: %TRUE if the timer is running, %FALSE otherwise
248  * Since: 2.62
249  **/
250 gboolean
251 g_timer_is_active (GTimer *timer)
252 {
253   g_return_val_if_fail (timer != NULL, FALSE);
254
255   return timer->active;
256 }
257
258 /**
259  * g_usleep:
260  * @microseconds: number of microseconds to pause
261  *
262  * Pauses the current thread for the given number of microseconds.
263  *
264  * There are 1 million microseconds per second (represented by the
265  * %G_USEC_PER_SEC macro). g_usleep() may have limited precision,
266  * depending on hardware and operating system; don't rely on the exact
267  * length of the sleep.
268  */
269 void
270 g_usleep (gulong microseconds)
271 {
272 #ifdef G_OS_WIN32
273   /* Round up to the next millisecond */
274   Sleep (microseconds ? (1 + (microseconds - 1) / 1000) : 0);
275 #else
276   struct timespec request, remaining;
277   request.tv_sec = microseconds / G_USEC_PER_SEC;
278   request.tv_nsec = 1000 * (microseconds % G_USEC_PER_SEC);
279   while (nanosleep (&request, &remaining) == -1 && errno == EINTR)
280     request = remaining;
281 #endif
282 }
283
284 /**
285  * g_time_val_add:
286  * @time_: a #GTimeVal
287  * @microseconds: number of microseconds to add to @time
288  *
289  * Adds the given number of microseconds to @time_. @microseconds can
290  * also be negative to decrease the value of @time_.
291  *
292  * Deprecated: 2.62: #GTimeVal is not year-2038-safe. Use `guint64` for
293  *    representing microseconds since the epoch, or use #GDateTime.
294  **/
295 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
296 void 
297 g_time_val_add (GTimeVal *time_, glong microseconds)
298 {
299   g_return_if_fail (time_ != NULL &&
300                     time_->tv_usec >= 0 &&
301                     time_->tv_usec < G_USEC_PER_SEC);
302
303   if (microseconds >= 0)
304     {
305       time_->tv_usec += microseconds % G_USEC_PER_SEC;
306       time_->tv_sec += microseconds / G_USEC_PER_SEC;
307       if (time_->tv_usec >= G_USEC_PER_SEC)
308        {
309          time_->tv_usec -= G_USEC_PER_SEC;
310          time_->tv_sec++;
311        }
312     }
313   else
314     {
315       microseconds *= -1;
316       time_->tv_usec -= microseconds % G_USEC_PER_SEC;
317       time_->tv_sec -= microseconds / G_USEC_PER_SEC;
318       if (time_->tv_usec < 0)
319        {
320          time_->tv_usec += G_USEC_PER_SEC;
321          time_->tv_sec--;
322        }      
323     }
324 }
325 G_GNUC_END_IGNORE_DEPRECATIONS
326
327 /* converts a broken down date representation, relative to UTC,
328  * to a timestamp; it uses timegm() if it's available.
329  */
330 static time_t
331 mktime_utc (struct tm *tm)
332 {
333   time_t retval;
334   
335 #ifndef HAVE_TIMEGM
336   static const gint days_before[] =
337   {
338     0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
339   };
340 #endif
341
342 #ifndef HAVE_TIMEGM
343   if (tm->tm_mon < 0 || tm->tm_mon > 11)
344     return (time_t) -1;
345
346   retval = (tm->tm_year - 70) * 365;
347   retval += (tm->tm_year - 68) / 4;
348   retval += days_before[tm->tm_mon] + tm->tm_mday - 1;
349   
350   if (tm->tm_year % 4 == 0 && tm->tm_mon < 2)
351     retval -= 1;
352   
353   retval = ((((retval * 24) + tm->tm_hour) * 60) + tm->tm_min) * 60 + tm->tm_sec;
354 #else
355   retval = timegm (tm);
356 #endif /* !HAVE_TIMEGM */
357   
358   return retval;
359 }
360
361 /**
362  * g_time_val_from_iso8601:
363  * @iso_date: an ISO 8601 encoded date string
364  * @time_: (out): a #GTimeVal
365  *
366  * Converts a string containing an ISO 8601 encoded date and time
367  * to a #GTimeVal and puts it into @time_.
368  *
369  * @iso_date must include year, month, day, hours, minutes, and
370  * seconds. It can optionally include fractions of a second and a time
371  * zone indicator. (In the absence of any time zone indication, the
372  * timestamp is assumed to be in local time.)
373  *
374  * Any leading or trailing space in @iso_date is ignored.
375  *
376  * This function was deprecated, along with #GTimeVal itself, in GLib 2.62.
377  * Equivalent functionality is available using code like:
378  * |[
379  * GDateTime *dt = g_date_time_new_from_iso8601 (iso8601_string, NULL);
380  * gint64 time_val = g_date_time_to_unix (dt);
381  * g_date_time_unref (dt);
382  * ]|
383  *
384  * Returns: %TRUE if the conversion was successful.
385  *
386  * Since: 2.12
387  * Deprecated: 2.62: #GTimeVal is not year-2038-safe. Use
388  *    g_date_time_new_from_iso8601() instead.
389  */
390 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
391 gboolean
392 g_time_val_from_iso8601 (const gchar *iso_date,
393                          GTimeVal    *time_)
394 {
395   struct tm tm = {0};
396   long val;
397   long mday, mon, year;
398   long hour, min, sec;
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, the first digit
404    * of the date, otherwise we don't have an ISO 8601 date
405    */
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 != '+')
413     return FALSE;
414
415   val = strtoul (iso_date, (char **)&iso_date, 10);
416   if (*iso_date == '-')
417     {
418       /* YYYY-MM-DD */
419       year = val;
420       iso_date++;
421
422       mon = strtoul (iso_date, (char **)&iso_date, 10);
423       if (*iso_date++ != '-')
424         return FALSE;
425       
426       mday = strtoul (iso_date, (char **)&iso_date, 10);
427     }
428   else
429     {
430       /* YYYYMMDD */
431       mday = val % 100;
432       mon = (val % 10000) / 100;
433       year = val / 10000;
434     }
435
436   /* Validation. */
437   if (year < 1900 || year > G_MAXINT)
438     return FALSE;
439   if (mon < 1 || mon > 12)
440     return FALSE;
441   if (mday < 1 || mday > 31)
442     return FALSE;
443
444   tm.tm_mday = mday;
445   tm.tm_mon = mon - 1;
446   tm.tm_year = year - 1900;
447
448   if (*iso_date != 'T')
449     return FALSE;
450
451   iso_date++;
452
453   /* If there is a 'T' then there has to be a time */
454   if (!g_ascii_isdigit (*iso_date))
455     return FALSE;
456
457   val = strtoul (iso_date, (char **)&iso_date, 10);
458   if (*iso_date == ':')
459     {
460       /* hh:mm:ss */
461       hour = val;
462       iso_date++;
463       min = strtoul (iso_date, (char **)&iso_date, 10);
464       
465       if (*iso_date++ != ':')
466         return FALSE;
467       
468       sec = strtoul (iso_date, (char **)&iso_date, 10);
469     }
470   else
471     {
472       /* hhmmss */
473       sec = val % 100;
474       min = (val % 10000) / 100;
475       hour = val / 10000;
476     }
477
478   /* Validation. Allow up to 2 leap seconds when validating @sec. */
479   if (hour > 23)
480     return FALSE;
481   if (min > 59)
482     return FALSE;
483   if (sec > 61)
484     return FALSE;
485
486   tm.tm_hour = hour;
487   tm.tm_min = min;
488   tm.tm_sec = sec;
489
490   time_->tv_usec = 0;
491   
492   if (*iso_date == ',' || *iso_date == '.')
493     {
494       glong mul = 100000;
495
496       while (mul >= 1 && g_ascii_isdigit (*++iso_date))
497         {
498           time_->tv_usec += (*iso_date - '0') * mul;
499           mul /= 10;
500         }
501
502       /* Skip any remaining digits after we’ve reached our limit of precision. */
503       while (g_ascii_isdigit (*iso_date))
504         iso_date++;
505     }
506     
507   /* Now parse the offset and convert tm to a time_t */
508   if (*iso_date == 'Z')
509     {
510       iso_date++;
511       time_->tv_sec = mktime_utc (&tm);
512     }
513   else if (*iso_date == '+' || *iso_date == '-')
514     {
515       gint sign = (*iso_date == '+') ? -1 : 1;
516       
517       val = strtoul (iso_date + 1, (char **)&iso_date, 10);
518       
519       if (*iso_date == ':')
520         {
521           /* hh:mm */
522           hour = val;
523           min = strtoul (iso_date + 1, (char **)&iso_date, 10);
524         }
525       else
526         {
527           /* hhmm */
528           hour = val / 100;
529           min = val % 100;
530         }
531
532       if (hour > 99)
533         return FALSE;
534       if (min > 59)
535         return FALSE;
536
537       time_->tv_sec = mktime_utc (&tm) + (time_t) (60 * (gint64) (60 * hour + min) * sign);
538     }
539   else
540     {
541       /* No "Z" or offset, so local time */
542       tm.tm_isdst = -1; /* locale selects DST */
543       time_->tv_sec = mktime (&tm);
544     }
545
546   while (g_ascii_isspace (*iso_date))
547     iso_date++;
548
549   return *iso_date == '\0';
550 }
551 G_GNUC_END_IGNORE_DEPRECATIONS
552
553 /**
554  * g_time_val_to_iso8601:
555  * @time_: a #GTimeVal
556  * 
557  * Converts @time_ into an RFC 3339 encoded string, relative to the
558  * Coordinated Universal Time (UTC). This is one of the many formats
559  * allowed by ISO 8601.
560  *
561  * ISO 8601 allows a large number of date/time formats, with or without
562  * punctuation and optional elements. The format returned by this function
563  * is a complete date and time, with optional punctuation included, the
564  * UTC time zone represented as "Z", and the @tv_usec part included if
565  * and only if it is nonzero, i.e. either
566  * "YYYY-MM-DDTHH:MM:SSZ" or "YYYY-MM-DDTHH:MM:SS.fffffZ".
567  *
568  * This corresponds to the Internet date/time format defined by
569  * [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt),
570  * and to either of the two most-precise formats defined by
571  * the W3C Note
572  * [Date and Time Formats](http://www.w3.org/TR/NOTE-datetime-19980827).
573  * Both of these documents are profiles of ISO 8601.
574  *
575  * Use g_date_time_format() or g_strdup_printf() if a different
576  * variation of ISO 8601 format is required.
577  *
578  * If @time_ represents a date which is too large to fit into a `struct tm`,
579  * %NULL will be returned. This is platform dependent. Note also that since
580  * `GTimeVal` stores the number of seconds as a `glong`, on 32-bit systems it
581  * is subject to the year 2038 problem. Accordingly, since GLib 2.62, this
582  * function has been deprecated. Equivalent functionality is available using:
583  * |[
584  * GDateTime *dt = g_date_time_new_from_unix_utc (time_val);
585  * iso8601_string = g_date_time_format_iso8601 (dt);
586  * g_date_time_unref (dt);
587  * ]|
588  *
589  * The return value of g_time_val_to_iso8601() has been nullable since GLib
590  * 2.54; before then, GLib would crash under the same conditions.
591  *
592  * Returns: (nullable): a newly allocated string containing an ISO 8601 date,
593  *    or %NULL if @time_ was too large
594  *
595  * Since: 2.12
596  * Deprecated: 2.62: #GTimeVal is not year-2038-safe. Use
597  *    g_date_time_format_iso8601(dt) instead.
598  */
599 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
600 gchar *
601 g_time_val_to_iso8601 (GTimeVal *time_)
602 {
603   gchar *retval;
604   struct tm *tm;
605 #ifdef HAVE_GMTIME_R
606   struct tm tm_;
607 #endif
608   time_t secs;
609
610   g_return_val_if_fail (time_ != NULL &&
611                         time_->tv_usec >= 0 &&
612                         time_->tv_usec < G_USEC_PER_SEC, NULL);
613
614   secs = time_->tv_sec;
615 #ifdef _WIN32
616   tm = gmtime (&secs);
617 #else
618 #ifdef HAVE_GMTIME_R
619   tm = gmtime_r (&secs, &tm_);
620 #else
621   tm = gmtime (&secs);
622 #endif
623 #endif
624
625   /* If the gmtime() call has failed, time_->tv_sec is too big. */
626   if (tm == NULL)
627     return NULL;
628
629   if (time_->tv_usec != 0)
630     {
631       /* ISO 8601 date and time format, with fractionary seconds:
632        *   YYYY-MM-DDTHH:MM:SS.MMMMMMZ
633        */
634       retval = g_strdup_printf ("%4d-%02d-%02dT%02d:%02d:%02d.%06ldZ",
635                                 tm->tm_year + 1900,
636                                 tm->tm_mon + 1,
637                                 tm->tm_mday,
638                                 tm->tm_hour,
639                                 tm->tm_min,
640                                 tm->tm_sec,
641                                 time_->tv_usec);
642     }
643   else
644     {
645       /* ISO 8601 date and time format:
646        *   YYYY-MM-DDTHH:MM:SSZ
647        */
648       retval = g_strdup_printf ("%4d-%02d-%02dT%02d:%02d:%02dZ",
649                                 tm->tm_year + 1900,
650                                 tm->tm_mon + 1,
651                                 tm->tm_mday,
652                                 tm->tm_hour,
653                                 tm->tm_min,
654                                 tm->tm_sec);
655     }
656   
657   return retval;
658 }
659 G_GNUC_END_IGNORE_DEPRECATIONS