* MODULES.html.sh (Support for systems lacking POSIX:2001): New
[gnulib.git] / lib / gethrxtime.c
1 /* gethrxtime -- get high resolution real time
2
3    Copyright (C) 2005, 2006, 2007 Free Software Foundation, Inc.
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2, or (at your option)
8    any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software Foundation,
17    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
18
19 /* Written by Paul Eggert.  */
20
21 #include <config.h>
22
23 #include "gethrxtime.h"
24
25 #include <sys/time.h>
26 #include "timespec.h"
27
28 /* Get the current time, as a count of the number of nanoseconds since
29    an arbitrary epoch (e.g., the system boot time).  Prefer a
30    high-resolution clock that is not subject to resetting or
31    drifting.  */
32
33 xtime_t
34 gethrxtime (void)
35 {
36 #if HAVE_NANOUPTIME
37   {
38     struct timespec ts;
39     nanouptime (&ts);
40     return xtime_make (ts.tv_sec, ts.tv_nsec);
41   }
42 #else
43
44 # if defined CLOCK_MONOTONIC && HAVE_CLOCK_GETTIME
45   {
46     struct timespec ts;
47     if (clock_gettime (CLOCK_MONOTONIC, &ts) == 0)
48       return xtime_make (ts.tv_sec, ts.tv_nsec);
49   }
50 # endif
51
52 # if HAVE_MICROUPTIME
53   {
54     struct timeval tv;
55     microuptime (&tv);
56     return xtime_make (tv.tv_sec, 1000 * tv.tv_usec);
57   }
58
59 # else
60   /* No monotonically increasing clocks are available; fall back on a
61      clock that might jump backwards, since it's the best we can do.  */
62   {
63     struct timespec ts;
64     gettime (&ts);
65     return xtime_make (ts.tv_sec, ts.tv_nsec);
66   }
67 # endif
68 #endif
69 }