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