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