1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * SPDX-License-Identifier: LGPL-2.1-or-later
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.
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.
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/>.
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/.
32 #include "glibconfig.h"
38 #endif /* G_OS_UNIX */
40 #ifdef HAVE_SYS_TIME_H
46 #endif /* G_OS_WIN32 */
50 #endif /* G_OS_WIN32 */
55 #include "gstrfuncs.h"
56 #include "gtestutils.h"
62 * @short_description: keep track of elapsed time
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.
73 * Opaque datatype that records a start time.
86 * Creates a new timer, and starts timing (i.e. g_timer_start() is
87 * implicitly called for you).
89 * Returns: a new #GTimer.
96 timer = g_new (GTimer, 1);
99 timer->start = g_get_monotonic_time ();
106 * @timer: a #GTimer to destroy.
108 * Destroys a timer, freeing associated resources.
111 g_timer_destroy (GTimer *timer)
113 g_return_if_fail (timer != NULL);
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.
128 g_timer_start (GTimer *timer)
130 g_return_if_fail (timer != NULL);
132 timer->active = TRUE;
134 timer->start = g_get_monotonic_time ();
141 * Marks an end time, so calls to g_timer_elapsed() will return the
142 * difference between this end time and the start time.
145 g_timer_stop (GTimer *timer)
147 g_return_if_fail (timer != NULL);
149 timer->active = FALSE;
151 timer->end = g_get_monotonic_time ();
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()
163 g_timer_reset (GTimer *timer)
165 g_return_if_fail (timer != NULL);
167 timer->start = g_get_monotonic_time ();
174 * Resumes a timer that has previously been stopped with
175 * g_timer_stop(). g_timer_stop() must be called before using this
181 g_timer_continue (GTimer *timer)
185 g_return_if_fail (timer != NULL);
186 g_return_if_fail (timer->active == FALSE);
188 /* Get elapsed time and reset timer start time
189 * to the current time minus the previously
193 elapsed = timer->end - timer->start;
195 timer->start = g_get_monotonic_time ();
197 timer->start -= elapsed;
199 timer->active = TRUE;
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
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.
216 * Returns: seconds elapsed as a floating point value, including any
220 g_timer_elapsed (GTimer *timer,
221 gulong *microseconds)
226 g_return_val_if_fail (timer != NULL, 0);
229 timer->end = g_get_monotonic_time ();
231 elapsed = timer->end - timer->start;
233 total = elapsed / 1e6;
236 *microseconds = elapsed % 1000000;
245 * Exposes whether the timer is currently active.
247 * Returns: %TRUE if the timer is running, %FALSE otherwise
251 g_timer_is_active (GTimer *timer)
253 g_return_val_if_fail (timer != NULL, FALSE);
255 return timer->active;
260 * @microseconds: number of microseconds to pause
262 * Pauses the current thread for the given number of microseconds.
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.
270 g_usleep (gulong microseconds)
273 /* Round up to the next millisecond */
274 Sleep (microseconds ? (1 + (microseconds - 1) / 1000) : 0);
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)
286 * @time_: a #GTimeVal
287 * @microseconds: number of microseconds to add to @time
289 * Adds the given number of microseconds to @time_. @microseconds can
290 * also be negative to decrease the value of @time_.
292 * Deprecated: 2.62: #GTimeVal is not year-2038-safe. Use `guint64` for
293 * representing microseconds since the epoch, or use #GDateTime.
295 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
297 g_time_val_add (GTimeVal *time_, glong microseconds)
299 g_return_if_fail (time_ != NULL &&
300 time_->tv_usec >= 0 &&
301 time_->tv_usec < G_USEC_PER_SEC);
303 if (microseconds >= 0)
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)
309 time_->tv_usec -= G_USEC_PER_SEC;
316 time_->tv_usec -= microseconds % G_USEC_PER_SEC;
317 time_->tv_sec -= microseconds / G_USEC_PER_SEC;
318 if (time_->tv_usec < 0)
320 time_->tv_usec += G_USEC_PER_SEC;
325 G_GNUC_END_IGNORE_DEPRECATIONS
327 /* converts a broken down date representation, relative to UTC,
328 * to a timestamp; it uses timegm() if it's available.
331 mktime_utc (struct tm *tm)
336 static const gint days_before[] =
338 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
343 if (tm->tm_mon < 0 || tm->tm_mon > 11)
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;
350 if (tm->tm_year % 4 == 0 && tm->tm_mon < 2)
353 retval = ((((retval * 24) + tm->tm_hour) * 60) + tm->tm_min) * 60 + tm->tm_sec;
355 retval = timegm (tm);
356 #endif /* !HAVE_TIMEGM */
362 * g_time_val_from_iso8601:
363 * @iso_date: an ISO 8601 encoded date string
364 * @time_: (out): a #GTimeVal
366 * Converts a string containing an ISO 8601 encoded date and time
367 * to a #GTimeVal and puts it into @time_.
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.)
374 * Any leading or trailing space in @iso_date is ignored.
376 * This function was deprecated, along with #GTimeVal itself, in GLib 2.62.
377 * Equivalent functionality is available using code like:
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);
384 * Returns: %TRUE if the conversion was successful.
387 * Deprecated: 2.62: #GTimeVal is not year-2038-safe. Use
388 * g_date_time_new_from_iso8601() instead.
390 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
392 g_time_val_from_iso8601 (const gchar *iso_date,
397 long mday, mon, year;
400 g_return_val_if_fail (iso_date != NULL, FALSE);
401 g_return_val_if_fail (time_ != NULL, FALSE);
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
406 while (g_ascii_isspace (*iso_date))
409 if (*iso_date == '\0')
412 if (!g_ascii_isdigit (*iso_date) && *iso_date != '+')
415 val = strtoul (iso_date, (char **)&iso_date, 10);
416 if (*iso_date == '-')
422 mon = strtoul (iso_date, (char **)&iso_date, 10);
423 if (*iso_date++ != '-')
426 mday = strtoul (iso_date, (char **)&iso_date, 10);
432 mon = (val % 10000) / 100;
437 if (year < 1900 || year > G_MAXINT)
439 if (mon < 1 || mon > 12)
441 if (mday < 1 || mday > 31)
446 tm.tm_year = year - 1900;
448 if (*iso_date != 'T')
453 /* If there is a 'T' then there has to be a time */
454 if (!g_ascii_isdigit (*iso_date))
457 val = strtoul (iso_date, (char **)&iso_date, 10);
458 if (*iso_date == ':')
463 min = strtoul (iso_date, (char **)&iso_date, 10);
465 if (*iso_date++ != ':')
468 sec = strtoul (iso_date, (char **)&iso_date, 10);
474 min = (val % 10000) / 100;
478 /* Validation. Allow up to 2 leap seconds when validating @sec. */
492 if (*iso_date == ',' || *iso_date == '.')
496 while (mul >= 1 && g_ascii_isdigit (*++iso_date))
498 time_->tv_usec += (*iso_date - '0') * mul;
502 /* Skip any remaining digits after we’ve reached our limit of precision. */
503 while (g_ascii_isdigit (*iso_date))
507 /* Now parse the offset and convert tm to a time_t */
508 if (*iso_date == 'Z')
511 time_->tv_sec = mktime_utc (&tm);
513 else if (*iso_date == '+' || *iso_date == '-')
515 gint sign = (*iso_date == '+') ? -1 : 1;
517 val = strtoul (iso_date + 1, (char **)&iso_date, 10);
519 if (*iso_date == ':')
523 min = strtoul (iso_date + 1, (char **)&iso_date, 10);
537 time_->tv_sec = mktime_utc (&tm) + (time_t) (60 * (gint64) (60 * hour + min) * sign);
541 /* No "Z" or offset, so local time */
542 tm.tm_isdst = -1; /* locale selects DST */
543 time_->tv_sec = mktime (&tm);
546 while (g_ascii_isspace (*iso_date))
549 return *iso_date == '\0';
551 G_GNUC_END_IGNORE_DEPRECATIONS
554 * g_time_val_to_iso8601:
555 * @time_: a #GTimeVal
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.
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".
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
572 * [Date and Time Formats](http://www.w3.org/TR/NOTE-datetime-19980827).
573 * Both of these documents are profiles of ISO 8601.
575 * Use g_date_time_format() or g_strdup_printf() if a different
576 * variation of ISO 8601 format is required.
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:
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);
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.
592 * Returns: (nullable): a newly allocated string containing an ISO 8601 date,
593 * or %NULL if @time_ was too large
596 * Deprecated: 2.62: #GTimeVal is not year-2038-safe. Use
597 * g_date_time_format_iso8601(dt) instead.
599 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
601 g_time_val_to_iso8601 (GTimeVal *time_)
610 g_return_val_if_fail (time_ != NULL &&
611 time_->tv_usec >= 0 &&
612 time_->tv_usec < G_USEC_PER_SEC, NULL);
614 secs = time_->tv_sec;
619 tm = gmtime_r (&secs, &tm_);
625 /* If the gmtime() call has failed, time_->tv_sec is too big. */
629 if (time_->tv_usec != 0)
631 /* ISO 8601 date and time format, with fractionary seconds:
632 * YYYY-MM-DDTHH:MM:SS.MMMMMMZ
634 retval = g_strdup_printf ("%4d-%02d-%02dT%02d:%02d:%02d.%06ldZ",
645 /* ISO 8601 date and time format:
646 * YYYY-MM-DDTHH:MM:SSZ
648 retval = g_strdup_printf ("%4d-%02d-%02dT%02d:%02d:%02dZ",
659 G_GNUC_END_IGNORE_DEPRECATIONS