Coverage Report

Created: 2026-07-16 07:10

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/glib/glib/gtimer.c
Line
Count
Source
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*
90
g_timer_new (void)
91
0
{
92
0
  GTimer *timer;
93
94
0
  timer = g_new (GTimer, 1);
95
0
  timer->active = TRUE;
96
97
0
  timer->start = g_get_monotonic_time ();
98
99
0
  return timer;
100
0
}
101
102
/**
103
 * g_timer_destroy:
104
 * @timer: a #GTimer to destroy.
105
 *
106
 * Destroys a timer, freeing associated resources.
107
 **/
108
void
109
g_timer_destroy (GTimer *timer)
110
0
{
111
0
  g_return_if_fail (timer != NULL);
112
113
0
  g_free (timer);
114
0
}
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
126
g_timer_start (GTimer *timer)
127
0
{
128
0
  g_return_if_fail (timer != NULL);
129
130
0
  timer->active = TRUE;
131
132
0
  timer->start = g_get_monotonic_time ();
133
0
}
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
143
g_timer_stop (GTimer *timer)
144
0
{
145
0
  g_return_if_fail (timer != NULL);
146
147
0
  timer->active = FALSE;
148
149
0
  timer->end = g_get_monotonic_time ();
150
0
}
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
161
g_timer_reset (GTimer *timer)
162
0
{
163
0
  g_return_if_fail (timer != NULL);
164
165
0
  timer->start = g_get_monotonic_time ();
166
0
}
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
179
g_timer_continue (GTimer *timer)
180
0
{
181
0
  guint64 elapsed;
182
183
0
  g_return_if_fail (timer != NULL);
184
0
  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
0
  elapsed = timer->end - timer->start;
192
193
0
  timer->start = g_get_monotonic_time ();
194
195
0
  timer->start -= elapsed;
196
197
0
  timer->active = TRUE;
198
0
}
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
218
g_timer_elapsed (GTimer *timer,
219
     gulong *microseconds)
220
0
{
221
0
  gdouble total;
222
0
  gint64 elapsed;
223
224
0
  g_return_val_if_fail (timer != NULL, 0);
225
226
0
  if (timer->active)
227
0
    timer->end = g_get_monotonic_time ();
228
229
0
  elapsed = timer->end - timer->start;
230
231
0
  total = elapsed / 1e6;
232
233
0
  if (microseconds)
234
0
    *microseconds = elapsed % 1000000;
235
236
0
  return total;
237
0
}
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
249
g_timer_is_active (GTimer *timer)
250
0
{
251
0
  g_return_val_if_fail (timer != NULL, FALSE);
252
253
0
  return timer->active;
254
0
}
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
268
g_usleep (gulong microseconds)
269
0
{
270
#ifdef G_OS_WIN32
271
  /* Round up to the next millisecond */
272
  Sleep (microseconds ? (1 + (microseconds - 1) / 1000) : 0);
273
#else
274
0
  struct timespec request, remaining;
275
0
  request.tv_sec = microseconds / G_USEC_PER_SEC;
276
0
  request.tv_nsec = 1000 * (microseconds % G_USEC_PER_SEC);
277
0
  while (nanosleep (&request, &remaining) == -1 && errno == EINTR)
278
0
    request = remaining;
279
0
#endif
280
0
}
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 
295
g_time_val_add (GTimeVal *time_, glong microseconds)
296
0
{
297
0
  g_return_if_fail (time_->tv_usec >= 0 && time_->tv_usec < G_USEC_PER_SEC);
298
299
0
  if (microseconds >= 0)
300
0
    {
301
0
      time_->tv_usec += microseconds % G_USEC_PER_SEC;
302
0
      time_->tv_sec += microseconds / G_USEC_PER_SEC;
303
0
      if (time_->tv_usec >= G_USEC_PER_SEC)
304
0
       {
305
0
         time_->tv_usec -= G_USEC_PER_SEC;
306
0
         time_->tv_sec++;
307
0
       }
308
0
    }
309
0
  else
310
0
    {
311
0
      microseconds *= -1;
312
0
      time_->tv_usec -= microseconds % G_USEC_PER_SEC;
313
0
      time_->tv_sec -= microseconds / G_USEC_PER_SEC;
314
0
      if (time_->tv_usec < 0)
315
0
       {
316
0
         time_->tv_usec += G_USEC_PER_SEC;
317
0
         time_->tv_sec--;
318
0
       }      
319
0
    }
320
0
}
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
327
mktime_utc (struct tm *tm)
328
0
{
329
0
  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
0
  retval = timegm (tm);
352
0
#endif /* !HAVE_TIMEGM */
353
  
354
0
  return retval;
355
0
}
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
388
g_time_val_from_iso8601 (const gchar *iso_date,
389
       GTimeVal    *time_)
390
0
{
391
0
  struct tm tm = {0};
392
0
  long val;
393
0
  long mday, mon, year;
394
0
  long hour, min, sec;
395
396
0
  g_return_val_if_fail (iso_date != NULL, FALSE);
397
0
  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
0
  while (g_ascii_isspace (*iso_date))
403
0
    iso_date++;
404
405
0
  if (*iso_date == '\0')
406
0
    return FALSE;
407
408
0
  if (!g_ascii_isdigit (*iso_date) && *iso_date != '+')
409
0
    return FALSE;
410
411
0
  val = strtoul (iso_date, (char **)&iso_date, 10);
412
0
  if (*iso_date == '-')
413
0
    {
414
      /* YYYY-MM-DD */
415
0
      year = val;
416
0
      iso_date++;
417
418
0
      mon = strtoul (iso_date, (char **)&iso_date, 10);
419
0
      if (*iso_date++ != '-')
420
0
        return FALSE;
421
      
422
0
      mday = strtoul (iso_date, (char **)&iso_date, 10);
423
0
    }
424
0
  else
425
0
    {
426
      /* YYYYMMDD */
427
0
      mday = val % 100;
428
0
      mon = (val % 10000) / 100;
429
0
      year = val / 10000;
430
0
    }
431
432
  /* Validation. */
433
0
  if (year < 1900 || year > G_MAXINT)
434
0
    return FALSE;
435
0
  if (mon < 1 || mon > 12)
436
0
    return FALSE;
437
0
  if (mday < 1 || mday > 31)
438
0
    return FALSE;
439
440
0
  tm.tm_mday = mday;
441
0
  tm.tm_mon = mon - 1;
442
0
  tm.tm_year = year - 1900;
443
444
0
  if (*iso_date != 'T')
445
0
    return FALSE;
446
447
0
  iso_date++;
448
449
  /* If there is a 'T' then there has to be a time */
450
0
  if (!g_ascii_isdigit (*iso_date))
451
0
    return FALSE;
452
453
0
  val = strtoul (iso_date, (char **)&iso_date, 10);
454
0
  if (*iso_date == ':')
455
0
    {
456
      /* hh:mm:ss */
457
0
      hour = val;
458
0
      iso_date++;
459
0
      min = strtoul (iso_date, (char **)&iso_date, 10);
460
      
461
0
      if (*iso_date++ != ':')
462
0
        return FALSE;
463
      
464
0
      sec = strtoul (iso_date, (char **)&iso_date, 10);
465
0
    }
466
0
  else
467
0
    {
468
      /* hhmmss */
469
0
      sec = val % 100;
470
0
      min = (val % 10000) / 100;
471
0
      hour = val / 10000;
472
0
    }
473
474
  /* Validation. Allow up to 2 leap seconds when validating @sec. */
475
0
  if (hour > 23)
476
0
    return FALSE;
477
0
  if (min > 59)
478
0
    return FALSE;
479
0
  if (sec > 61)
480
0
    return FALSE;
481
482
0
  tm.tm_hour = hour;
483
0
  tm.tm_min = min;
484
0
  tm.tm_sec = sec;
485
486
0
  time_->tv_usec = 0;
487
  
488
0
  if (*iso_date == ',' || *iso_date == '.')
489
0
    {
490
0
      glong mul = 100000;
491
492
0
      while (mul >= 1 && g_ascii_isdigit (*++iso_date))
493
0
        {
494
0
          time_->tv_usec += (*iso_date - '0') * mul;
495
0
          mul /= 10;
496
0
        }
497
498
      /* Skip any remaining digits after we’ve reached our limit of precision. */
499
0
      while (g_ascii_isdigit (*iso_date))
500
0
        iso_date++;
501
0
    }
502
    
503
  /* Now parse the offset and convert tm to a time_t */
504
0
  if (*iso_date == 'Z')
505
0
    {
506
0
      iso_date++;
507
0
      time_->tv_sec = mktime_utc (&tm);
508
0
    }
509
0
  else if (*iso_date == '+' || *iso_date == '-')
510
0
    {
511
0
      gint sign = (*iso_date == '+') ? -1 : 1;
512
      
513
0
      val = strtoul (iso_date + 1, (char **)&iso_date, 10);
514
      
515
0
      if (*iso_date == ':')
516
0
        {
517
          /* hh:mm */
518
0
          hour = val;
519
0
          min = strtoul (iso_date + 1, (char **)&iso_date, 10);
520
0
        }
521
0
      else
522
0
        {
523
          /* hhmm */
524
0
          hour = val / 100;
525
0
          min = val % 100;
526
0
        }
527
528
0
      if (hour > 99)
529
0
        return FALSE;
530
0
      if (min > 59)
531
0
        return FALSE;
532
533
0
      time_->tv_sec = mktime_utc (&tm) + (time_t) (60 * (gint64) (60 * hour + min) * sign);
534
0
    }
535
0
  else
536
0
    {
537
      /* No "Z" or offset, so local time */
538
0
      tm.tm_isdst = -1; /* locale selects DST */
539
0
      time_->tv_sec = mktime (&tm);
540
0
    }
541
542
0
  while (g_ascii_isspace (*iso_date))
543
0
    iso_date++;
544
545
0
  return *iso_date == '\0';
546
0
}
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 *
597
g_time_val_to_iso8601 (GTimeVal *time_)
598
0
{
599
0
  gchar *retval;
600
0
  struct tm *tm;
601
0
#ifdef HAVE_GMTIME_R
602
0
  struct tm tm_;
603
0
#endif
604
0
  time_t secs;
605
606
0
  g_return_val_if_fail (time_->tv_usec >= 0 && time_->tv_usec < G_USEC_PER_SEC, NULL);
607
608
0
  secs = time_->tv_sec;
609
#ifdef _WIN32
610
  tm = gmtime (&secs);
611
#else
612
0
#ifdef HAVE_GMTIME_R
613
0
  tm = gmtime_r (&secs, &tm_);
614
#else
615
  tm = gmtime (&secs);
616
#endif
617
0
#endif
618
619
  /* If the gmtime() call has failed, time_->tv_sec is too big. */
620
0
  if (tm == NULL)
621
0
    return NULL;
622
623
0
  if (time_->tv_usec != 0)
624
0
    {
625
      /* ISO 8601 date and time format, with fractionary seconds:
626
       *   YYYY-MM-DDTHH:MM:SS.MMMMMMZ
627
       */
628
0
      retval = g_strdup_printf ("%4d-%02d-%02dT%02d:%02d:%02d.%06ldZ",
629
0
                                tm->tm_year + 1900,
630
0
                                tm->tm_mon + 1,
631
0
                                tm->tm_mday,
632
0
                                tm->tm_hour,
633
0
                                tm->tm_min,
634
0
                                tm->tm_sec,
635
0
                                time_->tv_usec);
636
0
    }
637
0
  else
638
0
    {
639
      /* ISO 8601 date and time format:
640
       *   YYYY-MM-DDTHH:MM:SSZ
641
       */
642
0
      retval = g_strdup_printf ("%4d-%02d-%02dT%02d:%02d:%02dZ",
643
0
                                tm->tm_year + 1900,
644
0
                                tm->tm_mon + 1,
645
0
                                tm->tm_mday,
646
0
                                tm->tm_hour,
647
0
                                tm->tm_min,
648
0
                                tm->tm_sec);
649
0
    }
650
  
651
0
  return retval;
652
0
}
653
G_GNUC_END_IGNORE_DEPRECATIONS