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