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.1 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, see <http://www.gnu.org/licenses/>.
16 */
17
18 /*
19 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
20 * file for a list of people on the GLib Team. See the ChangeLog
21 * files for a list of changes. These files are distributed with
22 * GLib at ftp://ftp.gtk.org/pub/gtk/.
23 */
24
25 /*
26 * MT safe
27 */
28
29 #include "config.h"
30 #include "glibconfig.h"
31
32 #include <stdlib.h>
33
34 #ifdef G_OS_UNIX
35 #include <unistd.h>
36 #endif /* G_OS_UNIX */
37
38 #ifdef HAVE_SYS_TIME_H
39 #include <sys/time.h>
40 #endif
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 *
84 * Creates a new timer, and starts timing (i.e. g_timer_start() is
85 * implicitly called for you).
86 *
87 * Returns: a new #GTimer.
88 **/
89 GTimer*
g_timer_new(void)90 g_timer_new (void)
91 {
92 GTimer *timer;
93
94 timer = g_new (GTimer, 1);
95 timer->active = TRUE;
96
97 timer->start = g_get_monotonic_time ();
98
99 return timer;
100 }
101
102 /**
103 * g_timer_destroy:
104 * @timer: a #GTimer to destroy.
105 *
106 * Destroys a timer, freeing associated resources.
107 **/
108 void
g_timer_destroy(GTimer * timer)109 g_timer_destroy (GTimer *timer)
110 {
111 g_return_if_fail (timer != NULL);
112
113 g_free (timer);
114 }
115
116 /**
117 * g_timer_start:
118 * @timer: a #GTimer.
119 *
120 * Marks a start time, so that future calls to g_timer_elapsed() will
121 * report the time since g_timer_start() was called. g_timer_new()
122 * automatically marks the start time, so no need to call
123 * g_timer_start() immediately after creating the timer.
124 **/
125 void
g_timer_start(GTimer * timer)126 g_timer_start (GTimer *timer)
127 {
128 g_return_if_fail (timer != NULL);
129
130 timer->active = TRUE;
131
132 timer->start = g_get_monotonic_time ();
133 }
134
135 /**
136 * g_timer_stop:
137 * @timer: a #GTimer.
138 *
139 * Marks an end time, so calls to g_timer_elapsed() will return the
140 * difference between this end time and the start time.
141 **/
142 void
g_timer_stop(GTimer * timer)143 g_timer_stop (GTimer *timer)
144 {
145 g_return_if_fail (timer != NULL);
146
147 timer->active = FALSE;
148
149 timer->end = g_get_monotonic_time ();
150 }
151
152 /**
153 * g_timer_reset:
154 * @timer: a #GTimer.
155 *
156 * This function is useless; it's fine to call g_timer_start() on an
157 * already-started timer to reset the start time, so g_timer_reset()
158 * serves no purpose.
159 **/
160 void
g_timer_reset(GTimer * timer)161 g_timer_reset (GTimer *timer)
162 {
163 g_return_if_fail (timer != NULL);
164
165 timer->start = g_get_monotonic_time ();
166 }
167
168 /**
169 * g_timer_continue:
170 * @timer: a #GTimer.
171 *
172 * Resumes a timer that has previously been stopped with
173 * g_timer_stop(). g_timer_stop() must be called before using this
174 * function.
175 *
176 * Since: 2.4
177 **/
178 void
g_timer_continue(GTimer * timer)179 g_timer_continue (GTimer *timer)
180 {
181 guint64 elapsed;
182
183 g_return_if_fail (timer != NULL);
184 g_return_if_fail (timer->active == FALSE);
185
186 /* Get elapsed time and reset timer start time
187 * to the current time minus the previously
188 * elapsed interval.
189 */
190
191 elapsed = timer->end - timer->start;
192
193 timer->start = g_get_monotonic_time ();
194
195 timer->start -= elapsed;
196
197 timer->active = TRUE;
198 }
199
200 /**
201 * g_timer_elapsed:
202 * @timer: a #GTimer.
203 * @microseconds: return location for the fractional part of seconds
204 * elapsed, in microseconds (that is, the total number
205 * of microseconds elapsed, modulo 1000000), or %NULL
206 *
207 * If @timer has been started but not stopped, obtains the time since
208 * the timer was started. If @timer has been stopped, obtains the
209 * elapsed time between the time it was started and the time it was
210 * stopped. The return value is the number of seconds elapsed,
211 * including any fractional part. The @microseconds out parameter is
212 * essentially useless.
213 *
214 * Returns: seconds elapsed as a floating point value, including any
215 * fractional part.
216 **/
217 gdouble
g_timer_elapsed(GTimer * timer,gulong * microseconds)218 g_timer_elapsed (GTimer *timer,
219 gulong *microseconds)
220 {
221 gdouble total;
222 gint64 elapsed;
223
224 g_return_val_if_fail (timer != NULL, 0);
225
226 if (timer->active)
227 timer->end = g_get_monotonic_time ();
228
229 elapsed = timer->end - timer->start;
230
231 total = elapsed / 1e6;
232
233 if (microseconds)
234 *microseconds = elapsed % 1000000;
235
236 return total;
237 }
238
239 /**
240 * g_timer_is_active:
241 * @timer: a #GTimer.
242 *
243 * Exposes whether the timer is currently active.
244 *
245 * Returns: %TRUE if the timer is running, %FALSE otherwise
246 * Since: 2.62
247 **/
248 gboolean
g_timer_is_active(GTimer * timer)249 g_timer_is_active (GTimer *timer)
250 {
251 g_return_val_if_fail (timer != NULL, FALSE);
252
253 return timer->active;
254 }
255
256 /**
257 * g_usleep:
258 * @microseconds: number of microseconds to pause
259 *
260 * Pauses the current thread for the given number of microseconds.
261 *
262 * There are 1 million microseconds per second (represented by the
263 * #G_USEC_PER_SEC macro). g_usleep() may have limited precision,
264 * depending on hardware and operating system; don't rely on the exact
265 * length of the sleep.
266 */
267 void
g_usleep(gulong microseconds)268 g_usleep (gulong microseconds)
269 {
270 #ifdef G_OS_WIN32
271 /* Round up to the next millisecond */
272 Sleep (microseconds ? (1 + (microseconds - 1) / 1000) : 0);
273 #else
274 struct timespec request, remaining;
275 request.tv_sec = microseconds / G_USEC_PER_SEC;
276 request.tv_nsec = 1000 * (microseconds % G_USEC_PER_SEC);
277 while (nanosleep (&request, &remaining) == -1 && errno == EINTR)
278 request = remaining;
279 #endif
280 }
281
282 /**
283 * g_time_val_add:
284 * @time_: a #GTimeVal
285 * @microseconds: number of microseconds to add to @time
286 *
287 * Adds the given number of microseconds to @time_. @microseconds can
288 * also be negative to decrease the value of @time_.
289 *
290 * Deprecated: 2.62: #GTimeVal is not year-2038-safe. Use `guint64` for
291 * representing microseconds since the epoch, or use #GDateTime.
292 **/
293 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
294 void
g_time_val_add(GTimeVal * time_,glong microseconds)295 g_time_val_add (GTimeVal *time_, glong microseconds)
296 {
297 g_return_if_fail (time_->tv_usec >= 0 && time_->tv_usec < G_USEC_PER_SEC);
298
299 if (microseconds >= 0)
300 {
301 time_->tv_usec += microseconds % G_USEC_PER_SEC;
302 time_->tv_sec += microseconds / G_USEC_PER_SEC;
303 if (time_->tv_usec >= G_USEC_PER_SEC)
304 {
305 time_->tv_usec -= G_USEC_PER_SEC;
306 time_->tv_sec++;
307 }
308 }
309 else
310 {
311 microseconds *= -1;
312 time_->tv_usec -= microseconds % G_USEC_PER_SEC;
313 time_->tv_sec -= microseconds / G_USEC_PER_SEC;
314 if (time_->tv_usec < 0)
315 {
316 time_->tv_usec += G_USEC_PER_SEC;
317 time_->tv_sec--;
318 }
319 }
320 }
321 G_GNUC_END_IGNORE_DEPRECATIONS
322
323 /* converts a broken down date representation, relative to UTC,
324 * to a timestamp; it uses timegm() if it's available.
325 */
326 static time_t
mktime_utc(struct tm * tm)327 mktime_utc (struct tm *tm)
328 {
329 time_t retval;
330
331 #ifndef HAVE_TIMEGM
332 static const gint days_before[] =
333 {
334 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
335 };
336 #endif
337
338 #ifndef HAVE_TIMEGM
339 if (tm->tm_mon < 0 || tm->tm_mon > 11)
340 return (time_t) -1;
341
342 retval = (tm->tm_year - 70) * 365;
343 retval += (tm->tm_year - 68) / 4;
344 retval += days_before[tm->tm_mon] + tm->tm_mday - 1;
345
346 if (tm->tm_year % 4 == 0 && tm->tm_mon < 2)
347 retval -= 1;
348
349 retval = ((((retval * 24) + tm->tm_hour) * 60) + tm->tm_min) * 60 + tm->tm_sec;
350 #else
351 retval = timegm (tm);
352 #endif /* !HAVE_TIMEGM */
353
354 return retval;
355 }
356
357 /**
358 * g_time_val_from_iso8601:
359 * @iso_date: an ISO 8601 encoded date string
360 * @time_: (out): a #GTimeVal
361 *
362 * Converts a string containing an ISO 8601 encoded date and time
363 * to a #GTimeVal and puts it into @time_.
364 *
365 * @iso_date must include year, month, day, hours, minutes, and
366 * seconds. It can optionally include fractions of a second and a time
367 * zone indicator. (In the absence of any time zone indication, the
368 * timestamp is assumed to be in local time.)
369 *
370 * Any leading or trailing space in @iso_date is ignored.
371 *
372 * This function was deprecated, along with #GTimeVal itself, in GLib 2.62.
373 * Equivalent functionality is available using code like:
374 * |[
375 * GDateTime *dt = g_date_time_new_from_iso8601 (iso8601_string, NULL);
376 * gint64 time_val = g_date_time_to_unix (dt);
377 * g_date_time_unref (dt);
378 * ]|
379 *
380 * Returns: %TRUE if the conversion was successful.
381 *
382 * Since: 2.12
383 * Deprecated: 2.62: #GTimeVal is not year-2038-safe. Use
384 * g_date_time_new_from_iso8601() instead.
385 */
386 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
387 gboolean
g_time_val_from_iso8601(const gchar * iso_date,GTimeVal * time_)388 g_time_val_from_iso8601 (const gchar *iso_date,
389 GTimeVal *time_)
390 {
391 struct tm tm = {0};
392 long val;
393 long mday, mon, year;
394 long hour, min, sec;
395
396 g_return_val_if_fail (iso_date != NULL, FALSE);
397 g_return_val_if_fail (time_ != NULL, FALSE);
398
399 /* Ensure that the first character is a digit, the first digit
400 * of the date, otherwise we don't have an ISO 8601 date
401 */
402 while (g_ascii_isspace (*iso_date))
403 iso_date++;
404
405 if (*iso_date == '\0')
406 return FALSE;
407
408 if (!g_ascii_isdigit (*iso_date) && *iso_date != '+')
409 return FALSE;
410
411 val = strtoul (iso_date, (char **)&iso_date, 10);
412 if (*iso_date == '-')
413 {
414 /* YYYY-MM-DD */
415 year = val;
416 iso_date++;
417
418 mon = strtoul (iso_date, (char **)&iso_date, 10);
419 if (*iso_date++ != '-')
420 return FALSE;
421
422 mday = strtoul (iso_date, (char **)&iso_date, 10);
423 }
424 else
425 {
426 /* YYYYMMDD */
427 mday = val % 100;
428 mon = (val % 10000) / 100;
429 year = val / 10000;
430 }
431
432 /* Validation. */
433 if (year < 1900 || year > G_MAXINT)
434 return FALSE;
435 if (mon < 1 || mon > 12)
436 return FALSE;
437 if (mday < 1 || mday > 31)
438 return FALSE;
439
440 tm.tm_mday = mday;
441 tm.tm_mon = mon - 1;
442 tm.tm_year = year - 1900;
443
444 if (*iso_date != 'T')
445 return FALSE;
446
447 iso_date++;
448
449 /* If there is a 'T' then there has to be a time */
450 if (!g_ascii_isdigit (*iso_date))
451 return FALSE;
452
453 val = strtoul (iso_date, (char **)&iso_date, 10);
454 if (*iso_date == ':')
455 {
456 /* hh:mm:ss */
457 hour = val;
458 iso_date++;
459 min = strtoul (iso_date, (char **)&iso_date, 10);
460
461 if (*iso_date++ != ':')
462 return FALSE;
463
464 sec = strtoul (iso_date, (char **)&iso_date, 10);
465 }
466 else
467 {
468 /* hhmmss */
469 sec = val % 100;
470 min = (val % 10000) / 100;
471 hour = val / 10000;
472 }
473
474 /* Validation. Allow up to 2 leap seconds when validating @sec. */
475 if (hour > 23)
476 return FALSE;
477 if (min > 59)
478 return FALSE;
479 if (sec > 61)
480 return FALSE;
481
482 tm.tm_hour = hour;
483 tm.tm_min = min;
484 tm.tm_sec = sec;
485
486 time_->tv_usec = 0;
487
488 if (*iso_date == ',' || *iso_date == '.')
489 {
490 glong mul = 100000;
491
492 while (mul >= 1 && g_ascii_isdigit (*++iso_date))
493 {
494 time_->tv_usec += (*iso_date - '0') * mul;
495 mul /= 10;
496 }
497
498 /* Skip any remaining digits after we’ve reached our limit of precision. */
499 while (g_ascii_isdigit (*iso_date))
500 iso_date++;
501 }
502
503 /* Now parse the offset and convert tm to a time_t */
504 if (*iso_date == 'Z')
505 {
506 iso_date++;
507 time_->tv_sec = mktime_utc (&tm);
508 }
509 else if (*iso_date == '+' || *iso_date == '-')
510 {
511 gint sign = (*iso_date == '+') ? -1 : 1;
512
513 val = strtoul (iso_date + 1, (char **)&iso_date, 10);
514
515 if (*iso_date == ':')
516 {
517 /* hh:mm */
518 hour = val;
519 min = strtoul (iso_date + 1, (char **)&iso_date, 10);
520 }
521 else
522 {
523 /* hhmm */
524 hour = val / 100;
525 min = val % 100;
526 }
527
528 if (hour > 99)
529 return FALSE;
530 if (min > 59)
531 return FALSE;
532
533 time_->tv_sec = mktime_utc (&tm) + (time_t) (60 * (gint64) (60 * hour + min) * sign);
534 }
535 else
536 {
537 /* No "Z" or offset, so local time */
538 tm.tm_isdst = -1; /* locale selects DST */
539 time_->tv_sec = mktime (&tm);
540 }
541
542 while (g_ascii_isspace (*iso_date))
543 iso_date++;
544
545 return *iso_date == '\0';
546 }
547 G_GNUC_END_IGNORE_DEPRECATIONS
548
549 /**
550 * g_time_val_to_iso8601:
551 * @time_: a #GTimeVal
552 *
553 * Converts @time_ into an RFC 3339 encoded string, relative to the
554 * Coordinated Universal Time (UTC). This is one of the many formats
555 * allowed by ISO 8601.
556 *
557 * ISO 8601 allows a large number of date/time formats, with or without
558 * punctuation and optional elements. The format returned by this function
559 * is a complete date and time, with optional punctuation included, the
560 * UTC time zone represented as "Z", and the @tv_usec part included if
561 * and only if it is nonzero, i.e. either
562 * "YYYY-MM-DDTHH:MM:SSZ" or "YYYY-MM-DDTHH:MM:SS.fffffZ".
563 *
564 * This corresponds to the Internet date/time format defined by
565 * [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt),
566 * and to either of the two most-precise formats defined by
567 * the W3C Note
568 * [Date and Time Formats](http://www.w3.org/TR/NOTE-datetime-19980827).
569 * Both of these documents are profiles of ISO 8601.
570 *
571 * Use g_date_time_format() or g_strdup_printf() if a different
572 * variation of ISO 8601 format is required.
573 *
574 * If @time_ represents a date which is too large to fit into a `struct tm`,
575 * %NULL will be returned. This is platform dependent. Note also that since
576 * `GTimeVal` stores the number of seconds as a `glong`, on 32-bit systems it
577 * is subject to the year 2038 problem. Accordingly, since GLib 2.62, this
578 * function has been deprecated. Equivalent functionality is available using:
579 * |[
580 * GDateTime *dt = g_date_time_new_from_unix_utc (time_val);
581 * iso8601_string = g_date_time_format_iso8601 (dt);
582 * g_date_time_unref (dt);
583 * ]|
584 *
585 * The return value of g_time_val_to_iso8601() has been nullable since GLib
586 * 2.54; before then, GLib would crash under the same conditions.
587 *
588 * Returns: (nullable): a newly allocated string containing an ISO 8601 date,
589 * or %NULL if @time_ was too large
590 *
591 * Since: 2.12
592 * Deprecated: 2.62: #GTimeVal is not year-2038-safe. Use
593 * g_date_time_format_iso8601(dt) instead.
594 */
595 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
596 gchar *
g_time_val_to_iso8601(GTimeVal * time_)597 g_time_val_to_iso8601 (GTimeVal *time_)
598 {
599 gchar *retval;
600 struct tm *tm;
601 #ifdef HAVE_GMTIME_R
602 struct tm tm_;
603 #endif
604 time_t secs;
605
606 g_return_val_if_fail (time_->tv_usec >= 0 && time_->tv_usec < G_USEC_PER_SEC, NULL);
607
608 secs = time_->tv_sec;
609 #ifdef _WIN32
610 tm = gmtime (&secs);
611 #else
612 #ifdef HAVE_GMTIME_R
613 tm = gmtime_r (&secs, &tm_);
614 #else
615 tm = gmtime (&secs);
616 #endif
617 #endif
618
619 /* If the gmtime() call has failed, time_->tv_sec is too big. */
620 if (tm == NULL)
621 return NULL;
622
623 if (time_->tv_usec != 0)
624 {
625 /* ISO 8601 date and time format, with fractionary seconds:
626 * YYYY-MM-DDTHH:MM:SS.MMMMMMZ
627 */
628 retval = g_strdup_printf ("%4d-%02d-%02dT%02d:%02d:%02d.%06ldZ",
629 tm->tm_year + 1900,
630 tm->tm_mon + 1,
631 tm->tm_mday,
632 tm->tm_hour,
633 tm->tm_min,
634 tm->tm_sec,
635 time_->tv_usec);
636 }
637 else
638 {
639 /* ISO 8601 date and time format:
640 * YYYY-MM-DDTHH:MM:SSZ
641 */
642 retval = g_strdup_printf ("%4d-%02d-%02dT%02d:%02d:%02dZ",
643 tm->tm_year + 1900,
644 tm->tm_mon + 1,
645 tm->tm_mday,
646 tm->tm_hour,
647 tm->tm_min,
648 tm->tm_sec);
649 }
650
651 return retval;
652 }
653 G_GNUC_END_IGNORE_DEPRECATIONS
654