gtimer.c 12.2 KB
Newer Older
Owen Taylor's avatar
Owen Taylor committed
1 2 3 4
/* GLIB - Library of useful routines for C programming
 * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
 *
 * This library is free software; you can redistribute it and/or
5
 * modify it under the terms of the GNU Lesser General Public
Owen Taylor's avatar
Owen Taylor committed
6 7 8 9 10 11
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12
 * Lesser General Public License for more details.
Owen Taylor's avatar
Owen Taylor committed
13
 *
14
 * You should have received a copy of the GNU Lesser General Public
Owen Taylor's avatar
Owen Taylor committed
15 16 17 18
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */
19

20
/*
21
 * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22 23
 * file for a list of people on the GLib Team.  See the ChangeLog
 * files for a list of changes.  These files are distributed with
Matthias Clasen's avatar
Matthias Clasen committed
24
 * GLib at ftp://ftp.gtk.org/pub/gtk/.
25 26
 */

Matthias Clasen's avatar
Matthias Clasen committed
27
/*
28 29 30
 * MT safe
 */

31
#include "config.h"
32
#include "glibconfig.h"
33

Emmanuele Bassi's avatar
Emmanuele Bassi committed
34 35
#include <stdlib.h>

36 37 38
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#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 */
Owen Taylor's avatar
Owen Taylor committed
47

48
#ifdef G_OS_WIN32
49
#include <windows.h>
50
#endif /* G_OS_WIN32 */
Owen Taylor's avatar
Owen Taylor committed
51

Matthias Clasen's avatar
Matthias Clasen committed
52 53 54 55 56
#include "gtimer.h"

#include "gmem.h"
#include "gstrfuncs.h"
#include "gtestutils.h"
57
#include "gmain.h"
58

59
/**
60
 * SECTION:timers
61 62 63 64 65 66 67 68 69 70 71 72 73 74
 * @title: Timers
 * @short_description: keep track of elapsed time
 *
 * #GTimer records a start time, and counts microseconds elapsed since
 * that time. This is done somewhat differently on different platforms,
 * and can be tricky to get exactly right, so #GTimer provides a
 * portable/convenient interface.
 **/

/**
 * GTimer:
 *
 * Opaque datatype that records a start time.
 **/
75
struct _GTimer
Owen Taylor's avatar
Owen Taylor committed
76
{
77 78
  guint64 start;
  guint64 end;
Owen Taylor's avatar
Owen Taylor committed
79

80 81
  guint active : 1;
};
Owen Taylor's avatar
Owen Taylor committed
82

83 84 85 86 87 88 89
/**
 * g_timer_new:
 * @Returns: a new #GTimer.
 *
 * Creates a new timer, and starts timing (i.e. g_timer_start() is
 * implicitly called for you).
 **/
Owen Taylor's avatar
Owen Taylor committed
90 91 92
GTimer*
g_timer_new (void)
{
93
  GTimer *timer;
Owen Taylor's avatar
Owen Taylor committed
94

95
  timer = g_new (GTimer, 1);
Owen Taylor's avatar
Owen Taylor committed
96 97
  timer->active = TRUE;

98
  timer->start = g_get_monotonic_time ();
Owen Taylor's avatar
Owen Taylor committed
99

100
  return timer;
Owen Taylor's avatar
Owen Taylor committed
101 102
}

103 104 105 106 107 108
/**
 * g_timer_destroy:
 * @timer: a #GTimer to destroy.
 *
 * Destroys a timer, freeing associated resources.
 **/
Owen Taylor's avatar
Owen Taylor committed
109 110 111
void
g_timer_destroy (GTimer *timer)
{
112
  g_return_if_fail (timer != NULL);
Owen Taylor's avatar
Owen Taylor committed
113 114 115 116

  g_free (timer);
}

117 118 119 120 121 122 123 124 125
/**
 * g_timer_start:
 * @timer: a #GTimer.
 *
 * Marks a start time, so that future calls to g_timer_elapsed() will
 * report the time since g_timer_start() was called. g_timer_new()
 * automatically marks the start time, so no need to call
 * g_timer_start() immediately after creating the timer.
 **/
Owen Taylor's avatar
Owen Taylor committed
126 127 128
void
g_timer_start (GTimer *timer)
{
129
  g_return_if_fail (timer != NULL);
Owen Taylor's avatar
Owen Taylor committed
130

131
  timer->active = TRUE;
132

133
  timer->start = g_get_monotonic_time ();
Owen Taylor's avatar
Owen Taylor committed
134 135
}

136 137 138 139 140 141 142
/**
 * g_timer_stop:
 * @timer: a #GTimer.
 *
 * Marks an end time, so calls to g_timer_elapsed() will return the
 * difference between this end time and the start time.
 **/
Owen Taylor's avatar
Owen Taylor committed
143 144 145
void
g_timer_stop (GTimer *timer)
{
146
  g_return_if_fail (timer != NULL);
Owen Taylor's avatar
Owen Taylor committed
147

148
  timer->active = FALSE;
149

150
  timer->end = g_get_monotonic_time ();
Owen Taylor's avatar
Owen Taylor committed
151 152
}

153 154 155 156 157 158 159 160
/**
 * g_timer_reset:
 * @timer: a #GTimer.
 *
 * This function is useless; it's fine to call g_timer_start() on an
 * already-started timer to reset the start time, so g_timer_reset()
 * serves no purpose.
 **/
Owen Taylor's avatar
Owen Taylor committed
161 162 163
void
g_timer_reset (GTimer *timer)
{
164
  g_return_if_fail (timer != NULL);
Owen Taylor's avatar
Owen Taylor committed
165

166
  timer->start = g_get_monotonic_time ();
Owen Taylor's avatar
Owen Taylor committed
167 168
}

169 170 171 172 173 174 175
/**
 * g_timer_continue:
 * @timer: a #GTimer.
 *
 * Resumes a timer that has previously been stopped with
 * g_timer_stop(). g_timer_stop() must be called before using this
 * function.
176 177
 *
 * Since: 2.4
178
 **/
179 180 181
void
g_timer_continue (GTimer *timer)
{
182
  guint64 elapsed;
183 184 185 186 187 188 189 190 191 192 193

  g_return_if_fail (timer != NULL);
  g_return_if_fail (timer->active == FALSE);

  /* Get elapsed time and reset timer start time
   *  to the current time minus the previously
   *  elapsed interval.
   */

  elapsed = timer->end - timer->start;

194
  timer->start = g_get_monotonic_time ();
195 196 197 198 199 200

  timer->start -= elapsed;

  timer->active = TRUE;
}

201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
/**
 * g_timer_elapsed:
 * @timer: a #GTimer.
 * @microseconds: return location for the fractional part of seconds
 *                elapsed, in microseconds (that is, the total number
 *                of microseconds elapsed, modulo 1000000), or %NULL
 * @Returns: seconds elapsed as a floating point value, including any
 *           fractional part.
 *
 * If @timer has been started but not stopped, obtains the time since
 * the timer was started. If @timer has been stopped, obtains the
 * elapsed time between the time it was started and the time it was
 * stopped. The return value is the number of seconds elapsed,
 * including any fractional part. The @microseconds out parameter is
 * essentially useless.
 **/
Owen Taylor's avatar
Owen Taylor committed
217 218
gdouble
g_timer_elapsed (GTimer *timer,
219
		 gulong *microseconds)
Owen Taylor's avatar
Owen Taylor committed
220 221
{
  gdouble total;
222
  gint64 elapsed;
Owen Taylor's avatar
Owen Taylor committed
223

224
  g_return_val_if_fail (timer != NULL, 0);
Owen Taylor's avatar
Owen Taylor committed
225

226
  if (timer->active)
227
    timer->end = g_get_monotonic_time ();
228

229 230
  elapsed = timer->end - timer->start;

Owen W. Taylor's avatar
Owen W. Taylor committed
231
  total = elapsed / 1e6;
232 233

  if (microseconds)
Owen W. Taylor's avatar
Owen W. Taylor committed
234
    *microseconds = elapsed % 1000000;
Owen Taylor's avatar
Owen Taylor committed
235 236 237

  return total;
}
238 239 240 241

void
g_usleep (gulong microseconds)
{
242
#ifdef G_OS_WIN32
243
  Sleep (microseconds / 1000);
244
#else
245 246 247
  struct timespec request, remaining;
  request.tv_sec = microseconds / G_USEC_PER_SEC;
  request.tv_nsec = 1000 * (microseconds % G_USEC_PER_SEC);
248 249
  while (nanosleep (&request, &remaining) == -1 && errno == EINTR)
    request = remaining;
250
#endif
251 252
}

253 254
/**
 * g_time_val_add:
255
 * @time_: a #GTimeVal
256 257
 * @microseconds: number of microseconds to add to @time
 *
258 259
 * Adds the given number of microseconds to @time_. @microseconds can
 * also be negative to decrease the value of @time_.
260 261
 **/
void 
262
g_time_val_add (GTimeVal *time_, glong microseconds)
263
{
264
  g_return_if_fail (time_->tv_usec >= 0 && time_->tv_usec < G_USEC_PER_SEC);
265 266 267

  if (microseconds >= 0)
    {
268 269 270
      time_->tv_usec += microseconds % G_USEC_PER_SEC;
      time_->tv_sec += microseconds / G_USEC_PER_SEC;
      if (time_->tv_usec >= G_USEC_PER_SEC)
271
       {
272 273
         time_->tv_usec -= G_USEC_PER_SEC;
         time_->tv_sec++;
274 275 276 277 278
       }
    }
  else
    {
      microseconds *= -1;
279 280 281
      time_->tv_usec -= microseconds % G_USEC_PER_SEC;
      time_->tv_sec -= microseconds / G_USEC_PER_SEC;
      if (time_->tv_usec < 0)
282
       {
283 284
         time_->tv_usec += G_USEC_PER_SEC;
         time_->tv_sec--;
285 286 287
       }      
    }
}
288

Emmanuele Bassi's avatar
Emmanuele Bassi committed
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
/* converts a broken down date representation, relative to UTC, to
 * a timestamp; it uses timegm() if it's available.
 */
static time_t
mktime_utc (struct tm *tm)
{
  time_t retval;
  
#ifndef HAVE_TIMEGM
  static const gint days_before[] =
  {
    0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
  };
#endif

#ifndef HAVE_TIMEGM
  if (tm->tm_mon < 0 || tm->tm_mon > 11)
    return (time_t) -1;

  retval = (tm->tm_year - 70) * 365;
  retval += (tm->tm_year - 68) / 4;
  retval += days_before[tm->tm_mon] + tm->tm_mday - 1;
  
312
  if (tm->tm_year % 4 == 0 && tm->tm_mon < 2)
Emmanuele Bassi's avatar
Emmanuele Bassi committed
313 314 315 316 317 318 319 320 321 322 323 324
    retval -= 1;
  
  retval = ((((retval * 24) + tm->tm_hour) * 60) + tm->tm_min) * 60 + tm->tm_sec;
#else
  retval = timegm (tm);
#endif /* !HAVE_TIMEGM */
  
  return retval;
}

/**
 * g_time_val_from_iso8601:
325
 * @iso_date: an ISO 8601 encoded date string
326
 * @time_: (out): a #GTimeVal
Emmanuele Bassi's avatar
Emmanuele Bassi committed
327 328 329 330
 *
 * Converts a string containing an ISO 8601 encoded date and time
 * to a #GTimeVal and puts it into @time_.
 *
331 332 333 334 335
 * @iso_date must include year, month, day, hours, minutes, and
 * seconds. It can optionally include fractions of a second and a time
 * zone indicator. (In the absence of any time zone indication, the
 * timestamp is assumed to be in local time.)
 *
Emmanuele Bassi's avatar
Emmanuele Bassi committed
336 337
 * Return value: %TRUE if the conversion was successful.
 *
Matthias Clasen's avatar
Matthias Clasen committed
338
 * Since: 2.12
Emmanuele Bassi's avatar
Emmanuele Bassi committed
339 340 341 342 343
 */
gboolean
g_time_val_from_iso8601 (const gchar *iso_date,
			 GTimeVal    *time_)
{
344
  struct tm tm = {0};
Emmanuele Bassi's avatar
Emmanuele Bassi committed
345 346 347 348 349
  long val;

  g_return_val_if_fail (iso_date != NULL, FALSE);
  g_return_val_if_fail (time_ != NULL, FALSE);

350 351 352 353 354
  /* Ensure that the first character is a digit,
   * the first digit of the date, otherwise we don't
   * have an ISO 8601 date */
  while (g_ascii_isspace (*iso_date))
    iso_date++;
355

356 357
  if (*iso_date == '\0')
    return FALSE;
358 359

  if (!g_ascii_isdigit (*iso_date) && *iso_date != '-' && *iso_date != '+')
360 361
    return FALSE;

Emmanuele Bassi's avatar
Emmanuele Bassi committed
362 363 364 365 366 367 368 369 370
  val = strtoul (iso_date, (char **)&iso_date, 10);
  if (*iso_date == '-')
    {
      /* YYYY-MM-DD */
      tm.tm_year = val - 1900;
      iso_date++;
      tm.tm_mon = strtoul (iso_date, (char **)&iso_date, 10) - 1;
      
      if (*iso_date++ != '-')
371
        return FALSE;
Emmanuele Bassi's avatar
Emmanuele Bassi committed
372 373 374 375 376 377 378 379 380 381 382
      
      tm.tm_mday = strtoul (iso_date, (char **)&iso_date, 10);
    }
  else
    {
      /* YYYYMMDD */
      tm.tm_mday = val % 100;
      tm.tm_mon = (val % 10000) / 100 - 1;
      tm.tm_year = val / 10000 - 1900;
    }

383 384 385 386 387 388 389 390
  if (*iso_date != 'T')
    {
      /* Date only */
      if (*iso_date == '\0')
        return TRUE;
      return FALSE;
    }

391
  iso_date++;
392 393 394

  /* If there is a 'T' then there has to be a time */
  if (!g_ascii_isdigit (*iso_date))
Emmanuele Bassi's avatar
Emmanuele Bassi committed
395
    return FALSE;
396

Emmanuele Bassi's avatar
Emmanuele Bassi committed
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
  val = strtoul (iso_date, (char **)&iso_date, 10);
  if (*iso_date == ':')
    {
      /* hh:mm:ss */
      tm.tm_hour = val;
      iso_date++;
      tm.tm_min = strtoul (iso_date, (char **)&iso_date, 10);
      
      if (*iso_date++ != ':')
        return FALSE;
      
      tm.tm_sec = strtoul (iso_date, (char **)&iso_date, 10);
    }
  else
    {
      /* hhmmss */
      tm.tm_sec = val % 100;
      tm.tm_min = (val % 10000) / 100;
      tm.tm_hour = val / 10000;
    }

418
  time_->tv_usec = 0;
Emmanuele Bassi's avatar
Emmanuele Bassi committed
419
  
420
  if (*iso_date == ',' || *iso_date == '.')
421 422 423 424 425 426 427 428 429
    {
      glong mul = 100000;

      while (g_ascii_isdigit (*++iso_date))
        {
          time_->tv_usec += (*iso_date - '0') * mul;
          mul /= 10;
        }
    }
Emmanuele Bassi's avatar
Emmanuele Bassi committed
430
    
431 432 433 434 435 436 437
  /* Now parse the offset and convert tm to a time_t */
  if (*iso_date == 'Z')
    {
      iso_date++;
      time_->tv_sec = mktime_utc (&tm);
    }
  else if (*iso_date == '+' || *iso_date == '-')
Emmanuele Bassi's avatar
Emmanuele Bassi committed
438 439 440
    {
      gint sign = (*iso_date == '+') ? -1 : 1;
      
441
      val = strtoul (iso_date + 1, (char **)&iso_date, 10);
Emmanuele Bassi's avatar
Emmanuele Bassi committed
442 443
      
      if (*iso_date == ':')
444
        val = 60 * val + strtoul (iso_date + 1, (char **)&iso_date, 10);
Emmanuele Bassi's avatar
Emmanuele Bassi committed
445 446 447
      else
        val = 60 * (val / 100) + (val % 100);

448 449 450 451 452
      time_->tv_sec = mktime_utc (&tm) + (time_t) (60 * val * sign);
    }
  else
    {
      /* No "Z" or offset, so local time */
453
      tm.tm_isdst = -1; /* locale selects DST */
454
      time_->tv_sec = mktime (&tm);
Emmanuele Bassi's avatar
Emmanuele Bassi committed
455 456
    }

457 458 459 460
  while (g_ascii_isspace (*iso_date))
    iso_date++;

  return *iso_date == '\0';
Emmanuele Bassi's avatar
Emmanuele Bassi committed
461 462 463 464 465 466
}

/**
 * g_time_val_to_iso8601:
 * @time_: a #GTimeVal
 * 
467
 * Converts @time_ into an ISO 8601 encoded string, relative to the
Emmanuele Bassi's avatar
Emmanuele Bassi committed
468 469
 * Coordinated Universal Time (UTC).
 *
470
 * Return value: a newly allocated string containing an ISO 8601 date
Emmanuele Bassi's avatar
Emmanuele Bassi committed
471
 *
Matthias Clasen's avatar
Matthias Clasen committed
472
 * Since: 2.12
Emmanuele Bassi's avatar
Emmanuele Bassi committed
473 474 475 476 477
 */
gchar *
g_time_val_to_iso8601 (GTimeVal *time_)
{
  gchar *retval;
478
  struct tm *tm;
479 480 481
#ifdef HAVE_GMTIME_R
  struct tm tm_;
#endif
482
  time_t secs;
483
  
Emmanuele Bassi's avatar
Emmanuele Bassi committed
484 485
  g_return_val_if_fail (time_->tv_usec >= 0 && time_->tv_usec < G_USEC_PER_SEC, NULL);

486
 secs = time_->tv_sec;
487
#ifdef _WIN32
488
 tm = gmtime (&secs);
489
#else
490
#ifdef HAVE_GMTIME_R
491
  tm = gmtime_r (&secs, &tm_);
492
#else
493
  tm = gmtime (&secs);
494
#endif
495
#endif
496 497 498

  if (time_->tv_usec != 0)
    {
499 500 501
      /* ISO 8601 date and time format, with fractionary seconds:
       *   YYYY-MM-DDTHH:MM:SS.MMMMMMZ
       */
502
      retval = g_strdup_printf ("%4d-%02d-%02dT%02d:%02d:%02d.%06ldZ",
503 504 505 506 507 508 509
                                tm->tm_year + 1900,
                                tm->tm_mon + 1,
                                tm->tm_mday,
                                tm->tm_hour,
                                tm->tm_min,
                                tm->tm_sec,
                                time_->tv_usec);
510 511 512
    }
  else
    {
513 514 515
      /* ISO 8601 date and time format:
       *   YYYY-MM-DDTHH:MM:SSZ
       */
516
      retval = g_strdup_printf ("%4d-%02d-%02dT%02d:%02d:%02dZ",
517 518 519 520 521 522
                                tm->tm_year + 1900,
                                tm->tm_mon + 1,
                                tm->tm_mday,
                                tm->tm_hour,
                                tm->tm_min,
                                tm->tm_sec);
523
    }
Emmanuele Bassi's avatar
Emmanuele Bassi committed
524 525 526
  
  return retval;
}