]> sjero.net Git - wget/blob - src/ptimer.c
[svn] Expect existence of C89 functions, as well as of select and gettimeofday.
[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 measure time in milliseconds, but the timings they return
43    are floating point numbers, so they can carry as much precision as
44    the underlying system timer supports.  For example, to measure the
45    time it takes to run a loop, you can use something like:
46
47      ptimer *tmr = ptimer_new ();
48      while (...)
49        ... loop ...
50      double msecs = ptimer_measure ();
51      printf ("The loop took %.2f ms\n", msecs);  */
52
53 #include <config.h>
54
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <errno.h>
59 #ifdef HAVE_UNISTD_H
60 # include <unistd.h>
61 #endif
62 #include <assert.h>
63 #include <time.h>
64
65 /* Cygwin currently (as of 2005-04-08, Cygwin 1.5.14) lacks clock_getres,
66    but still defines _POSIX_TIMERS!  Because of that we simply use the
67    Windows timers under Cygwin.  */
68 #ifdef __CYGWIN__
69 # include <windows.h>
70 #endif
71
72 #include "wget.h"
73 #include "ptimer.h"
74
75 /* Depending on the OS, one and only one of PTIMER_POSIX,
76    PTIMER_GETTIMEOFDAY, or PTIMER_WINDOWS will be defined.  */
77
78 #undef PTIMER_POSIX
79 #undef PTIMER_GETTIMEOFDAY
80 #undef PTIMER_WINDOWS
81
82 #if defined(WINDOWS) || defined(__CYGWIN__)
83 # define PTIMER_WINDOWS         /* use Windows timers */
84 #elif _POSIX_TIMERS - 0 > 0
85 # define PTIMER_POSIX           /* use POSIX timers (clock_gettime) */
86 #else
87 # define PTIMER_GETTIMEOFDAY    /* use gettimeofday */
88 #endif
89
90 #ifdef PTIMER_POSIX
91 /* Elapsed time measurement using POSIX timers: system time is held in
92    struct timespec, time is retrieved using clock_gettime, and
93    resolution using clock_getres.
94
95    This method is used on Unix systems that implement POSIX
96    timers.  */
97
98 typedef struct timespec ptimer_system_time;
99
100 #define IMPL_init posix_init
101 #define IMPL_measure posix_measure
102 #define IMPL_diff posix_diff
103 #define IMPL_resolution posix_resolution
104
105 /* clock_id to use for POSIX clocks.  This tries to use
106    CLOCK_MONOTONIC where available, CLOCK_REALTIME otherwise.  */
107 static int posix_clock_id;
108
109 /* Resolution of the clock, in milliseconds. */
110 static double posix_millisec_resolution;
111
112 /* Decide which clock_id to use.  */
113
114 static void
115 posix_init (void)
116 {
117   /* List of clocks we want to support: some systems support monotonic
118      clocks, Solaris has "high resolution" clock (sometimes
119      unavailable except to superuser), and all should support the
120      real-time clock.  */
121 #define NO_SYSCONF_CHECK -1
122   static const struct {
123     int id;
124     int sysconf_name;
125   } clocks[] = {
126 #if defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK - 0 >= 0
127     { CLOCK_MONOTONIC, _SC_MONOTONIC_CLOCK },
128 #endif
129 #ifdef CLOCK_HIGHRES
130     { CLOCK_HIGHRES, NO_SYSCONF_CHECK },
131 #endif
132     { CLOCK_REALTIME, NO_SYSCONF_CHECK },
133   };
134   int i;
135
136   /* Determine the clock we can use.  For a clock to be usable, it
137      must be confirmed with sysconf (where applicable) and with
138      clock_getres.  If no clock is found, CLOCK_REALTIME is used.  */
139
140   for (i = 0; i < countof (clocks); i++)
141     {
142       struct timespec r;
143       if (clocks[i].sysconf_name != NO_SYSCONF_CHECK)
144         if (sysconf (clocks[i].sysconf_name) < 0)
145           continue;             /* sysconf claims this clock is unavailable */
146       if (clock_getres (clocks[i].id, &r) < 0)
147         continue;               /* clock_getres doesn't work for this clock */
148       posix_clock_id = clocks[i].id;
149       posix_millisec_resolution = r.tv_sec * 1000.0 + r.tv_nsec / 1000000.0;
150       /* Guard against broken clock_getres returning nonsensical
151          values.  */
152       if (posix_millisec_resolution == 0)
153         posix_millisec_resolution = 1;
154       break;
155     }
156   if (i == countof (clocks))
157     {
158       /* If no clock was found, it means that clock_getres failed for
159          the realtime clock.  */
160       logprintf (LOG_NOTQUIET, _("Cannot get REALTIME clock frequency: %s\n"),
161                  strerror (errno));
162       /* Use CLOCK_REALTIME, but invent a plausible resolution. */
163       posix_clock_id = CLOCK_REALTIME;
164       posix_millisec_resolution = 1;
165     }
166 }
167
168 static inline void
169 posix_measure (ptimer_system_time *pst)
170 {
171   clock_gettime (posix_clock_id, pst);
172 }
173
174 static inline double
175 posix_diff (ptimer_system_time *pst1, ptimer_system_time *pst2)
176 {
177   return ((pst1->tv_sec - pst2->tv_sec) * 1000.0
178           + (pst1->tv_nsec - pst2->tv_nsec) / 1000000.0);
179 }
180
181 static inline double
182 posix_resolution (void)
183 {
184   return posix_millisec_resolution;
185 }
186 #endif  /* PTIMER_POSIX */
187
188 #ifdef PTIMER_GETTIMEOFDAY
189 /* Elapsed time measurement using gettimeofday: system time is held in
190    struct timeval, retrieved using gettimeofday, and resolution is
191    unknown.
192
193    This method is used Unix systems without POSIX timers.  */
194
195 typedef struct timeval ptimer_system_time;
196
197 #define IMPL_measure gettimeofday_measure
198 #define IMPL_diff gettimeofday_diff
199 #define IMPL_resolution gettimeofday_resolution
200
201 static inline void
202 gettimeofday_measure (ptimer_system_time *pst)
203 {
204   gettimeofday (pst, NULL);
205 }
206
207 static inline double
208 gettimeofday_diff (ptimer_system_time *pst1, ptimer_system_time *pst2)
209 {
210   return ((pst1->tv_sec - pst2->tv_sec) * 1000.0
211           + (pst1->tv_usec - pst2->tv_usec) / 1000.0);
212 }
213
214 static inline double
215 gettimeofday_resolution (void)
216 {
217   /* Granularity of gettimeofday varies wildly between architectures.
218      However, it appears that on modern machines it tends to be better
219      than 1ms.  Assume 100 usecs.  */
220   return 0.1;
221 }
222 #endif  /* PTIMER_GETTIMEOFDAY */
223
224 #ifdef PTIMER_WINDOWS
225 /* Elapsed time measurement on Windows: where high-resolution timers
226    are available, time is stored in a LARGE_INTEGER and retrieved
227    using QueryPerformanceCounter.  Otherwise, it is stored in a DWORD
228    and retrieved using GetTickCount.
229
230    This method is used on Windows.  */
231
232 typedef union {
233   DWORD lores;          /* In case GetTickCount is used */
234   LARGE_INTEGER hires;  /* In case high-resolution timer is used */
235 } ptimer_system_time;
236
237 #define IMPL_init windows_init
238 #define IMPL_measure windows_measure
239 #define IMPL_diff windows_diff
240 #define IMPL_resolution windows_resolution
241
242 /* Whether high-resolution timers are used.  Set by ptimer_initialize_once
243    the first time ptimer_new is called. */
244 static int windows_hires_timers;
245
246 /* Frequency of high-resolution timers -- number of updates per
247    millisecond.  Calculated the first time ptimer_new is called
248    provided that high-resolution timers are available. */
249 static double windows_hires_msfreq;
250
251 static void
252 windows_init (void)
253 {
254   LARGE_INTEGER freq;
255   freq.QuadPart = 0;
256   QueryPerformanceFrequency (&freq);
257   if (freq.QuadPart != 0)
258     {
259       windows_hires_timers = 1;
260       windows_hires_msfreq = (double) freq.QuadPart / 1000.0;
261     }
262 }
263
264 static inline void
265 windows_measure (ptimer_system_time *pst)
266 {
267   if (windows_hires_timers)
268     QueryPerformanceCounter (&pst->hires);
269   else
270     /* Where hires counters are not available, use GetTickCount rather
271        GetSystemTime, because it is unaffected by clock skew and
272        simpler to use.  Note that overflows don't affect us because we
273        never use absolute values of the ticker, only the
274        differences.  */
275     pst->lores = GetTickCount ();
276 }
277
278 static inline double
279 windows_diff (ptimer_system_time *pst1, ptimer_system_time *pst2)
280 {
281   if (windows_hires_timers)
282     return (pst1->hires.QuadPart - pst2->hires.QuadPart) / windows_hires_msfreq;
283   else
284     return pst1->lores - pst2->lores;
285 }
286
287 static double
288 windows_resolution (void)
289 {
290   if (windows_hires_timers)
291     return 1.0 / windows_hires_msfreq;
292   else
293     return 10;                  /* according to MSDN */
294 }
295 #endif  /* PTIMER_WINDOWS */
296 \f
297 /* The code below this point is independent of timer implementation. */
298
299 struct ptimer {
300   /* The starting point in time which, subtracted from the current
301      time, yields elapsed time. */
302   ptimer_system_time start;
303
304   /* The most recent elapsed time, calculated by ptimer_measure().
305      Measured in milliseconds.  */
306   double elapsed_last;
307
308   /* Approximately, the time elapsed between the true start of the
309      measurement and the time represented by START.  This is used for
310      adjustment when clock skew is detected.  */
311   double elapsed_pre_start;
312 };
313
314 /* Allocate a new timer and reset it.  Return the new timer. */
315
316 struct ptimer *
317 ptimer_new (void)
318 {
319   struct ptimer *pt = xnew0 (struct ptimer);
320 #ifdef IMPL_init
321   static int init_done;
322   if (!init_done)
323     {
324       init_done = 1;
325       IMPL_init ();
326     }
327 #endif
328   ptimer_reset (pt);
329   return pt;
330 }
331
332 /* Free the resources associated with the timer.  Its further use is
333    prohibited.  */
334
335 void
336 ptimer_destroy (struct ptimer *pt)
337 {
338   xfree (pt);
339 }
340
341 /* Reset timer PT.  This establishes the starting point from which
342    ptimer_read() will return the number of elapsed milliseconds.
343    It is allowed to reset a previously used timer.  */
344
345 void
346 ptimer_reset (struct ptimer *pt)
347 {
348   /* Set the start time to the current time. */
349   IMPL_measure (&pt->start);
350   pt->elapsed_last = 0;
351   pt->elapsed_pre_start = 0;
352 }
353
354 /* Measure the elapsed time since timer creation/reset and return it
355    to the caller.  The value remains stored for further reads by
356    ptimer_read.
357
358    This function causes the timer to call gettimeofday (or time(),
359    etc.) to update its idea of current time.  To get the elapsed
360    interval in milliseconds, use ptimer_read.
361
362    This function handles clock skew, i.e. time that moves backwards is
363    ignored.  */
364
365 double
366 ptimer_measure (struct ptimer *pt)
367 {
368   ptimer_system_time now;
369   double elapsed;
370
371   IMPL_measure (&now);
372   elapsed = pt->elapsed_pre_start + IMPL_diff (&now, &pt->start);
373
374   /* Ideally we'd just return the difference between NOW and
375      pt->start.  However, the system timer can be set back, and we
376      could return a value smaller than when we were last called, even
377      a negative value.  Both of these would confuse the callers, which
378      expect us to return monotonically nondecreasing values.
379
380      Therefore: if ELAPSED is smaller than its previous known value,
381      we reset pt->start to the current time and effectively start
382      measuring from this point.  But since we don't want the elapsed
383      value to start from zero, we set elapsed_pre_start to the last
384      elapsed time and increment all future calculations by that
385      amount.
386
387      This cannot happen with Windows and POSIX monotonic/highres
388      timers, but the check is not expensive.  */
389
390   if (elapsed < pt->elapsed_last)
391     {
392       pt->start = now;
393       pt->elapsed_pre_start = pt->elapsed_last;
394       elapsed = pt->elapsed_last;
395     }
396
397   pt->elapsed_last = elapsed;
398   return elapsed;
399 }
400
401 /* Return the elapsed time in milliseconds between the last call to
402    ptimer_reset and the last call to ptimer_update.  */
403
404 double
405 ptimer_read (const struct ptimer *pt)
406 {
407   return pt->elapsed_last;
408 }
409
410 /* Return the assessed resolution of the timer implementation, in
411    milliseconds.  This is used by code that tries to substitute a
412    better value for timers that have returned zero.  */
413
414 double
415 ptimer_resolution (void)
416 {
417   return IMPL_resolution ();
418 }