]> sjero.net Git - wget/blob - src/ptimer.c
Eschew config-post.h.
[wget] / src / ptimer.c
1 /* Portable timers.
2    Copyright (C) 2005, 2006, 2007 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 3 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, see <http://www.gnu.org/licenses/>.
18
19 In addition, as a special exception, the Free Software Foundation
20 gives permission to link the code of its release of Wget with the
21 OpenSSL project's "OpenSSL" library (or with modified versions of it
22 that use the same license as the "OpenSSL" library), and distribute
23 the linked executables.  You must obey the GNU General Public License
24 in all respects for all of the code used other than "OpenSSL".  If you
25 modify this file, you may extend this exception to your version of the
26 file, but you are not obligated to do so.  If you do not wish to do
27 so, delete this exception statement from your version.  */
28
29 /* This file implements "portable timers" (ptimers), objects that
30    measure elapsed time using the primitives most appropriate for the
31    underlying operating system.  The entry points are:
32
33      ptimer_new     -- creates a timer.
34      ptimer_reset   -- resets the timer's elapsed time to zero.
35      ptimer_measure -- measure and return the time elapsed since
36                        creation or last reset.
37      ptimer_read    -- reads the last measured elapsed value.
38      ptimer_destroy -- destroy the timer.
39      ptimer_granularity -- returns the approximate granularity of the timers.
40
41    Timers measure time in seconds, returning the timings as floating
42    point numbers, so they can carry as much precision as the
43    underlying system timer supports.  For example, to measure the time
44    it takes to run a loop, you can use something like:
45
46      ptimer *tmr = ptimer_new ();
47      while (...)
48        ... loop ...
49      double secs = ptimer_measure ();
50      printf ("The loop took %.2fs\n", secs);  */
51
52 #include "wget.h"
53
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <errno.h>
58 #ifdef HAVE_UNISTD_H
59 # include <unistd.h>
60 #endif
61 #include <time.h>
62 #ifdef HAVE_SYS_TIME_H
63 # include <sys/time.h>
64 #endif
65
66 /* Cygwin currently (as of 2005-04-08, Cygwin 1.5.14) lacks clock_getres,
67    but still defines _POSIX_TIMERS!  Because of that we simply use the
68    Windows timers under Cygwin.  */
69 #ifdef __CYGWIN__
70 # include <windows.h>
71 #endif
72
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, initialized in posix_init. */
110 static double posix_clock_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_clock_resolution = (double) r.tv_sec + r.tv_nsec / 1e9;
150       /* Guard against nonsense returned by a broken clock_getres.  */
151       if (posix_clock_resolution == 0)
152         posix_clock_resolution = 1e-3;
153       break;
154     }
155   if (i == countof (clocks))
156     {
157       /* If no clock was found, it means that clock_getres failed for
158          the realtime clock.  */
159       logprintf (LOG_NOTQUIET, _("Cannot get REALTIME clock frequency: %s\n"),
160                  strerror (errno));
161       /* Use CLOCK_REALTIME, but invent a plausible resolution. */
162       posix_clock_id = CLOCK_REALTIME;
163       posix_clock_resolution = 1e-3;
164     }
165 }
166
167 static inline void
168 posix_measure (ptimer_system_time *pst)
169 {
170   clock_gettime (posix_clock_id, pst);
171 }
172
173 static inline double
174 posix_diff (ptimer_system_time *pst1, ptimer_system_time *pst2)
175 {
176   return ((pst1->tv_sec - pst2->tv_sec)
177           + (pst1->tv_nsec - pst2->tv_nsec) / 1e9);
178 }
179
180 static inline double
181 posix_resolution (void)
182 {
183   return posix_clock_resolution;
184 }
185 #endif  /* PTIMER_POSIX */
186
187 #ifdef PTIMER_GETTIMEOFDAY
188 /* Elapsed time measurement using gettimeofday: system time is held in
189    struct timeval, retrieved using gettimeofday, and resolution is
190    unknown.
191
192    This method is used Unix systems without POSIX timers.  */
193
194 typedef struct timeval ptimer_system_time;
195
196 #define IMPL_measure gettimeofday_measure
197 #define IMPL_diff gettimeofday_diff
198 #define IMPL_resolution gettimeofday_resolution
199
200 static inline void
201 gettimeofday_measure (ptimer_system_time *pst)
202 {
203   gettimeofday (pst, NULL);
204 }
205
206 static inline double
207 gettimeofday_diff (ptimer_system_time *pst1, ptimer_system_time *pst2)
208 {
209   return ((pst1->tv_sec - pst2->tv_sec)
210           + (pst1->tv_usec - pst2->tv_usec) / 1e6);
211 }
212
213 static inline double
214 gettimeofday_resolution (void)
215 {
216   /* Granularity of gettimeofday varies wildly between architectures.
217      However, it appears that on modern machines it tends to be better
218      than 1ms.  Assume 100 usecs.  */
219   return 0.1;
220 }
221 #endif  /* PTIMER_GETTIMEOFDAY */
222
223 #ifdef PTIMER_WINDOWS
224 /* Elapsed time measurement on Windows: where high-resolution timers
225    are available, time is stored in a LARGE_INTEGER and retrieved
226    using QueryPerformanceCounter.  Otherwise, it is stored in a DWORD
227    and retrieved using GetTickCount.
228
229    This method is used on Windows.  */
230
231 typedef union {
232   DWORD lores;          /* In case GetTickCount is used */
233   LARGE_INTEGER hires;  /* In case high-resolution timer is used */
234 } ptimer_system_time;
235
236 #define IMPL_init windows_init
237 #define IMPL_measure windows_measure
238 #define IMPL_diff windows_diff
239 #define IMPL_resolution windows_resolution
240
241 /* Whether high-resolution timers are used.  Set by ptimer_initialize_once
242    the first time ptimer_new is called. */
243 static bool windows_hires_timers;
244
245 /* Frequency of high-resolution timers -- number of updates per
246    second.  Calculated the first time ptimer_new is called provided
247    that high-resolution timers are available. */
248 static double windows_hires_freq;
249
250 static void
251 windows_init (void)
252 {
253   LARGE_INTEGER freq;
254   freq.QuadPart = 0;
255   QueryPerformanceFrequency (&freq);
256   if (freq.QuadPart != 0)
257     {
258       windows_hires_timers = true;
259       windows_hires_freq = (double) freq.QuadPart;
260     }
261 }
262
263 static inline void
264 windows_measure (ptimer_system_time *pst)
265 {
266   if (windows_hires_timers)
267     QueryPerformanceCounter (&pst->hires);
268   else
269     /* Where hires counters are not available, use GetTickCount rather
270        GetSystemTime, because it is unaffected by clock skew and
271        simpler to use.  Note that overflows don't affect us because we
272        never use absolute values of the ticker, only the
273        differences.  */
274     pst->lores = GetTickCount ();
275 }
276
277 static inline double
278 windows_diff (ptimer_system_time *pst1, ptimer_system_time *pst2)
279 {
280   if (windows_hires_timers)
281     return (pst1->hires.QuadPart - pst2->hires.QuadPart) / windows_hires_freq;
282   else
283     return pst1->lores - pst2->lores;
284 }
285
286 static double
287 windows_resolution (void)
288 {
289   if (windows_hires_timers)
290     return 1.0 / windows_hires_freq;
291   else
292     return 10;                  /* according to MSDN */
293 }
294 #endif  /* PTIMER_WINDOWS */
295 \f
296 /* The code below this point is independent of timer implementation. */
297
298 struct ptimer {
299   /* The starting point in time which, subtracted from the current
300      time, yields elapsed time. */
301   ptimer_system_time start;
302
303   /* The most recent elapsed time, calculated by ptimer_measure().  */
304   double elapsed_last;
305
306   /* Approximately, the time elapsed between the true start of the
307      measurement and the time represented by START.  This is used for
308      adjustment when clock skew is detected.  */
309   double elapsed_pre_start;
310 };
311
312 /* Allocate a new timer and reset it.  Return the new timer. */
313
314 struct ptimer *
315 ptimer_new (void)
316 {
317   struct ptimer *pt = xnew0 (struct ptimer);
318 #ifdef IMPL_init
319   static bool init_done;
320   if (!init_done)
321     {
322       init_done = true;
323       IMPL_init ();
324     }
325 #endif
326   ptimer_reset (pt);
327   return pt;
328 }
329
330 /* Free the resources associated with the timer.  Its further use is
331    prohibited.  */
332
333 void
334 ptimer_destroy (struct ptimer *pt)
335 {
336   xfree (pt);
337 }
338
339 /* Reset timer PT.  This establishes the starting point from which
340    ptimer_measure() will return the elapsed time in seconds.  It is
341    allowed to reset a previously used timer.  */
342
343 void
344 ptimer_reset (struct ptimer *pt)
345 {
346   /* Set the start time to the current time. */
347   IMPL_measure (&pt->start);
348   pt->elapsed_last = 0;
349   pt->elapsed_pre_start = 0;
350 }
351
352 /* Measure the elapsed time since timer creation/reset.  This causes
353    the timer to internally call clock_gettime (or gettimeofday, etc.) 
354    to update its idea of current time.  The time is returned, but is
355    also stored for later access through ptimer_read().
356
357    This function handles clock skew, i.e. time that moves backwards is
358    ignored.  */
359
360 double
361 ptimer_measure (struct ptimer *pt)
362 {
363   ptimer_system_time now;
364   double elapsed;
365
366   IMPL_measure (&now);
367   elapsed = pt->elapsed_pre_start + IMPL_diff (&now, &pt->start);
368
369   /* Ideally we'd just return the difference between NOW and
370      pt->start.  However, the system timer can be set back, and we
371      could return a value smaller than when we were last called, even
372      a negative value.  Both of these would confuse the callers, which
373      expect us to return monotonically nondecreasing values.
374
375      Therefore: if ELAPSED is smaller than its previous known value,
376      we reset pt->start to the current time and effectively start
377      measuring from this point.  But since we don't want the elapsed
378      value to start from zero, we set elapsed_pre_start to the last
379      elapsed time and increment all future calculations by that
380      amount.
381
382      This cannot happen with Windows and POSIX monotonic/highres
383      timers, but the check is not expensive.  */
384
385   if (elapsed < pt->elapsed_last)
386     {
387       pt->start = now;
388       pt->elapsed_pre_start = pt->elapsed_last;
389       elapsed = pt->elapsed_last;
390     }
391
392   pt->elapsed_last = elapsed;
393   return elapsed;
394 }
395
396 /* Return the most recent elapsed time measured with ptimer_measure.
397    If ptimer_measure has not yet been called since the timer was
398    created or reset, this returns 0.  */
399
400 double
401 ptimer_read (const struct ptimer *pt)
402 {
403   return pt->elapsed_last;
404 }
405
406 /* Return the assessed resolution of the timer implementation, in
407    seconds.  This is used by code that tries to substitute a better
408    value for timers that have returned zero.  */
409
410 double
411 ptimer_resolution (void)
412 {
413   return IMPL_resolution ();
414 }