]> sjero.net Git - wget/blob - src/ptimer.c
[svn] Better selection of POSIX clocks.
[wget] / src / ptimer.c
1 /* Portable timers.
2    Copyright (C) 2005 Free Software Foundation, Inc.
3
4 This file is part of GNU Wget.
5
6 GNU Wget is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10
11 GNU Wget 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
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with Wget; if not, write to the Free Software
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20 In addition, as a special exception, the Free Software Foundation
21 gives permission to link the code of its release of Wget with the
22 OpenSSL project's "OpenSSL" library (or with modified versions of it
23 that use the same license as the "OpenSSL" library), and distribute
24 the linked executables.  You must obey the GNU General Public License
25 in all respects for all of the code used other than "OpenSSL".  If you
26 modify this file, you may extend this exception to your version of the
27 file, but you are not obligated to do so.  If you do not wish to do
28 so, delete this exception statement from your version.  */
29
30 /* This file implements "portable timers" (ptimers), objects that
31    measure elapsed time using the primitives most appropriate for the
32    underlying operating system.  The entry points are:
33
34      ptimer_new     -- creates a timer.
35      ptimer_reset   -- resets the timer's elapsed time to zero.
36      ptimer_measure -- measure and return the time elapsed since
37                        creation or last reset.
38      ptimer_read    -- reads the last measured elapsed value.
39      ptimer_destroy -- destroy the timer.
40      ptimer_granularity -- returns the approximate granularity of the timers.
41
42    Timers operate in milliseconds, but return floating point values
43    that can be more precise.  For example, to measure the time it
44    takes to run a loop, you can use something like:
45
46      ptimer *tmr = ptimer_new ();
47      while (...)
48        ... loop ...
49      double msecs = ptimer_measure ();
50      printf ("The loop took %.2f ms\n", msecs);  */
51
52 #include <config.h>
53
54 #include <stdio.h>
55 #include <stdlib.h>
56 #ifdef HAVE_STRING_H
57 # include <string.h>
58 #else  /* not HAVE_STRING_H */
59 # include <strings.h>
60 #endif /* not HAVE_STRING_H */
61 #include <sys/types.h>
62 #include <errno.h>
63 #ifdef HAVE_UNISTD_H
64 # include <unistd.h>
65 #endif
66 #include <assert.h>
67
68 #include "wget.h"
69 #include "ptimer.h"
70
71 #ifndef errno
72 extern int errno;
73 #endif
74
75 /* Depending on the OS and availability of gettimeofday(), one and
76    only one of PTIMER_POSIX, PTIMER_GETTIMEOFDAY, PTIMER_WINDOWS, or
77    PTIMER_TIME will be defined.  */
78
79 #undef PTIMER_POSIX
80 #undef PTIMER_GETTIMEOFDAY
81 #undef PTIMER_TIME
82 #undef PTIMER_WINDOWS
83
84 #ifdef WINDOWS
85 # define PTIMER_WINDOWS         /* use Windows timers */
86 #else
87 # if _POSIX_TIMERS > 0
88 #  define PTIMER_POSIX          /* use POSIX timers (clock_gettime) */
89 # else
90 #  ifdef HAVE_GETTIMEOFDAY
91 #   define PTIMER_GETTIMEOFDAY  /* use gettimeofday */
92 #  else
93 #   define PTIMER_TIME
94 #  endif
95 # endif
96 #endif
97
98 #ifdef PTIMER_POSIX
99 /* Elapsed time measurement using POSIX timers: system time is held in
100    struct timespec, time is retrieved using clock_gettime, and
101    resolution using clock_getres.
102
103    This method is used on Unix systems that implement POSIX
104    timers.  */
105
106 typedef struct timespec ptimer_system_time;
107
108 #define IMPL_init posix_init
109 #define IMPL_measure posix_measure
110 #define IMPL_diff posix_diff
111 #define IMPL_resolution posix_resolution
112
113 /* clock_id to use for POSIX clocks.  This tries to use
114    CLOCK_MONOTONIC where available, CLOCK_REALTIME otherwise.  */
115 static int posix_clock_id;
116
117 /* Resolution of the clock, in milliseconds. */
118 static double posix_millisec_resolution;
119
120 /* Decide which clock_id to use.  */
121
122 static void
123 posix_init (void)
124 {
125   /* List of clocks we want to support: some systems support monotonic
126      clocks, Solaris has "high resolution" clock (sometimes
127      unavailable except to superuser), and all should support the
128      real-time clock.  */
129 #define NO_SYSCONF_CHECK -1
130   static const struct {
131     int id;
132     int sysconf_name;
133   } clocks[] = {
134 #if defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
135     { CLOCK_MONOTONIC, _SC_MONOTONIC_CLOCK },
136 #endif
137 #ifdef CLOCK_HIGHRES
138     { CLOCK_HIGHRES, NO_SYSCONF_CHECK },
139 #endif
140     { CLOCK_REALTIME, NO_SYSCONF_CHECK },
141   };
142   int i;
143
144   /* Determine the clock we can use.  For a clock to be usable, it
145      must be confirmed with sysconf (where applicable) and with
146      clock_getres.  If no clock is found, CLOCK_REALTIME is used.  */
147
148   for (i = 0; i < countof (clocks); i++)
149     {
150       struct timespec r;
151       if (clocks[i].sysconf_name != NO_SYSCONF_CHECK)
152         if (sysconf (clocks[i].sysconf_name) < 0)
153           continue;             /* sysconf claims this clock is unavailable */
154       if (clock_getres (clocks[i].id, &r) < 0)
155         continue;               /* clock_getres doesn't work for this clock */
156       posix_clock_id = clocks[i].id;
157       posix_millisec_resolution = r.tv_sec * 1000.0 + r.tv_nsec / 1000000.0;
158       /* Guard against broken clock_getres returning nonsensical
159          values.  */
160       if (posix_millisec_resolution == 0)
161         posix_millisec_resolution = 1;
162       break;
163     }
164   if (i == countof (clocks))
165     {
166       /* If no clock was found, it means that clock_getres failed for
167          the realtime clock.  */
168       logprintf (LOG_NOTQUIET, _("Cannot get REALTIME clock frequency: %s\n"),
169                  strerror (errno));
170       /* Use CLOCK_REALTIME, but invent a plausible resolution. */
171       posix_clock_id = CLOCK_REALTIME;
172       posix_millisec_resolution = 1;
173     }
174 }
175
176 static inline void
177 posix_measure (ptimer_system_time *pst)
178 {
179   clock_gettime (posix_clock_id, pst);
180 }
181
182 static inline double
183 posix_diff (ptimer_system_time *pst1, ptimer_system_time *pst2)
184 {
185   return ((pst1->tv_sec - pst2->tv_sec) * 1000.0
186           + (pst1->tv_nsec - pst2->tv_nsec) / 1000000.0);
187 }
188
189 static inline double
190 posix_resolution (void)
191 {
192   return posix_millisec_resolution;
193 }
194 #endif  /* PTIMER_POSIX */
195
196 #ifdef PTIMER_GETTIMEOFDAY
197 /* Elapsed time measurement using gettimeofday: system time is held in
198    struct timeval, retrieved using gettimeofday, and resolution is
199    unknown.
200
201    This method is used Unix systems without POSIX timers.  */
202
203 typedef struct timeval ptimer_system_time;
204
205 #define IMPL_measure gettimeofday_measure
206 #define IMPL_diff gettimeofday_diff
207 #define IMPL_resolution gettimeofday_resolution
208
209 static inline void
210 gettimeofday_measure (ptimer_system_time *pst)
211 {
212   gettimeofday (pst, NULL);
213 }
214
215 static inline double
216 gettimeofday_diff (ptimer_system_time *pst1, ptimer_system_time *pst2)
217 {
218   return ((pst1->tv_sec - pst2->tv_sec) * 1000.0
219           + (pst1->tv_usec - pst2->tv_usec) / 1000.0);
220 }
221
222 static inline double
223 gettimeofday_resolution (void)
224 {
225   /* Granularity of gettimeofday varies wildly between architectures.
226      However, it appears that on modern machines it tends to be better
227      than 1ms.  Assume 100 usecs.  */
228   return 0.1;
229 }
230 #endif  /* PTIMER_GETTIMEOFDAY */
231
232 #ifdef PTIMER_TIME
233 /* Elapsed time measurement using the time(2) call: system time is
234    held in time_t, retrieved using time, and resolution is 1 second.
235
236    This method is a catch-all for non-Windows systems without
237    gettimeofday -- e.g. DOS or really old or non-standard Unix
238    systems.  */
239
240 typedef time_t ptimer_system_time;
241
242 #define IMPL_measure time_measure
243 #define IMPL_diff time_diff
244 #define IMPL_resolution time_resolution
245
246 static inline void
247 time_measure (ptimer_system_time *pst)
248 {
249   time (pst);
250 }
251
252 static inline double
253 time_diff (ptimer_system_time *pst1, ptimer_system_time *pst2)
254 {
255   return 1000.0 * (*pst1 - *pst2);
256 }
257
258 static inline double
259 time_resolution (void)
260 {
261   return 1;
262 }
263 #endif  /* PTIMER_TIME */
264
265 #ifdef PTIMER_WINDOWS
266 /* Elapsed time measurement on Windows: where high-resolution timers
267    are available, time is stored in a LARGE_INTEGER and retrieved
268    using QueryPerformanceCounter.  Otherwise, it is stored in a DWORD
269    and retrieved using GetTickCount.
270
271    This method is used on Windows.  */
272
273 typedef union {
274   DWORD lores;          /* In case GetTickCount is used */
275   LARGE_INTEGER hires;  /* In case high-resolution timer is used */
276 } ptimer_system_time;
277
278 #define IMPL_init windows_init
279 #define IMPL_measure windows_measure
280 #define IMPL_diff windows_diff
281 #define IMPL_resolution windows_resolution
282
283 /* Whether high-resolution timers are used.  Set by ptimer_initialize_once
284    the first time ptimer_new is called. */
285 static int windows_hires_timers;
286
287 /* Frequency of high-resolution timers -- number of updates per
288    millisecond.  Calculated the first time ptimer_new is called
289    provided that high-resolution timers are available. */
290 static double windows_hires_msfreq;
291
292 static void
293 windows_init (void)
294 {
295   LARGE_INTEGER freq;
296   freq.QuadPart = 0;
297   QueryPerformanceFrequency (&freq);
298   if (freq.QuadPart != 0)
299     {
300       windows_hires_timers = 1;
301       windows_hires_msfreq = (double) freq.QuadPart / 1000.0;
302     }
303 }
304
305 static inline void
306 windows_measure (ptimer_system_time *pst)
307 {
308   if (windows_hires_timers)
309     QueryPerformanceCounter (&pst->hires);
310   else
311     /* Where hires counters are not available, use GetTickCount rather
312        GetSystemTime, because it is unaffected by clock skew and
313        simpler to use.  Note that overflows don't affect us because we
314        never use absolute values of the ticker, only the
315        differences.  */
316     pst->lores = GetTickCount ();
317 }
318
319 static inline double
320 windows_diff (ptimer_system_time *pst1, ptimer_system_time *pst2)
321 {
322   if (windows_hires_timers)
323     return (pst1->hires.QuadPart - pst2->hires.QuadPart) / windows_hires_msfreq;
324   else
325     return pst1->lores - pst2->lores;
326 }
327
328 static double
329 windows_resolution (void)
330 {
331   if (windows_hires_timers)
332     return 1.0 / windows_hires_msfreq;
333   else
334     return 10;                  /* according to MSDN */
335 }
336 #endif  /* PTIMER_WINDOWS */
337 \f
338 /* The code below this point is independent of timer implementation. */
339
340 struct ptimer {
341   /* Whether the start time has been set. */
342   int initialized;
343
344   /* The starting point in time which, subtracted from the current
345      time, yields elapsed time. */
346   ptimer_system_time start;
347
348   /* The most recent elapsed time, calculated by ptimer_measure().
349      Measured in milliseconds.  */
350   double elapsed_last;
351
352   /* Approximately, the time elapsed between the true start of the
353      measurement and the time represented by START.  This is used for
354      adjustment when clock skew is detected.  */
355   double elapsed_pre_start;
356 };
357
358 /* Allocate a new timer and reset it.  Return the new timer. */
359
360 struct ptimer *
361 ptimer_new (void)
362 {
363   struct ptimer *wt = xnew0 (struct ptimer);
364 #ifdef IMPL_init
365   static int init_done;
366   if (!init_done)
367     {
368       init_done = 1;
369       IMPL_init ();
370     }
371 #endif
372   ptimer_reset (wt);
373   return wt;
374 }
375
376 /* Free the resources associated with the timer.  Its further use is
377    prohibited.  */
378
379 void
380 ptimer_destroy (struct ptimer *wt)
381 {
382   xfree (wt);
383 }
384
385 /* Reset timer WT.  This establishes the starting point from which
386    ptimer_read() will return the number of elapsed milliseconds.
387    It is allowed to reset a previously used timer.  */
388
389 void
390 ptimer_reset (struct ptimer *wt)
391 {
392   /* Set the start time to the current time. */
393   IMPL_measure (&wt->start);
394   wt->elapsed_last = 0;
395   wt->elapsed_pre_start = 0;
396   wt->initialized = 1;
397 }
398
399 /* Measure the elapsed time since timer creation/reset and return it
400    to the caller.  The value remains stored for further reads by
401    ptimer_read.
402
403    This function causes the timer to call gettimeofday (or time(),
404    etc.) to update its idea of current time.  To get the elapsed
405    interval in milliseconds, use ptimer_read.
406
407    This function handles clock skew, i.e. time that moves backwards is
408    ignored.  */
409
410 double
411 ptimer_measure (struct ptimer *wt)
412 {
413   ptimer_system_time now;
414   double elapsed;
415
416   assert (wt->initialized != 0);
417
418   IMPL_measure (&now);
419   elapsed = wt->elapsed_pre_start + IMPL_diff (&now, &wt->start);
420
421   /* Ideally we'd just return the difference between NOW and
422      wt->start.  However, the system timer can be set back, and we
423      could return a value smaller than when we were last called, even
424      a negative value.  Both of these would confuse the callers, which
425      expect us to return monotonically nondecreasing values.
426
427      Therefore: if ELAPSED is smaller than its previous known value,
428      we reset wt->start to the current time and effectively start
429      measuring from this point.  But since we don't want the elapsed
430      value to start from zero, we set elapsed_pre_start to the last
431      elapsed time and increment all future calculations by that
432      amount.
433
434      This cannot happen with Windows and POSIX monotonic/highres
435      timers, but the check is not expensive.  */
436
437   if (elapsed < wt->elapsed_last)
438     {
439       wt->start = now;
440       wt->elapsed_pre_start = wt->elapsed_last;
441       elapsed = wt->elapsed_last;
442     }
443
444   wt->elapsed_last = elapsed;
445   return elapsed;
446 }
447
448 /* Return the elapsed time in milliseconds between the last call to
449    ptimer_reset and the last call to ptimer_update.  */
450
451 double
452 ptimer_read (const struct ptimer *wt)
453 {
454   return wt->elapsed_last;
455 }
456
457 /* Return the assessed resolution of the timer implementation, in
458    milliseconds.  This is used by code that tries to substitute a
459    better value for timers that have returned zero.  */
460
461 double
462 ptimer_resolution (void)
463 {
464   return IMPL_resolution ();
465 }