544841f57c397c95782cc9048734cc7fae407935
[gnulib.git] / lib / xtime.h
1 /* xtime -- extended-resolution integer time stamps
2
3    Copyright (C) 2005-2006, 2009-2012 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 3 of the License, or
8    (at your option) 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, see <http://www.gnu.org/licenses/>.  */
17
18 /* Written by Paul Eggert.  */
19
20 #ifndef XTIME_H_
21 #define XTIME_H_ 1
22
23 _GL_INLINE_HEADER_BEGIN
24 #ifndef XTIME_INLINE
25 # define XTIME_INLINE _GL_INLINE
26 #endif
27
28 /* xtime_t is a signed type used for time stamps.  It is an integer
29    type that is a count of nanoseconds -- except for obsolescent hosts
30    without sufficiently-wide integers, where it is a count of
31    seconds.  */
32 #if HAVE_LONG_LONG_INT
33 typedef long long int xtime_t;
34 # define XTIME_PRECISION 1000000000
35 #else
36 # include <limits.h>
37 typedef long int xtime_t;
38 # if LONG_MAX >> 31 >> 31 == 0
39 #  define XTIME_PRECISION 1
40 # else
41 #  define XTIME_PRECISION 1000000000
42 # endif
43 #endif
44
45 #ifdef  __cplusplus
46 extern "C" {
47 #endif
48
49 /* Return an extended time value that contains S seconds and NS
50    nanoseconds, without any overflow checking.  */
51 XTIME_INLINE xtime_t
52 xtime_make (xtime_t s, long int ns)
53 {
54   if (XTIME_PRECISION == 1)
55     return s;
56   else
57     return XTIME_PRECISION * s + ns;
58 }
59
60 /* Return the number of seconds in T, which must be nonnegative.  */
61 XTIME_INLINE xtime_t
62 xtime_nonnegative_sec (xtime_t t)
63 {
64   return t / XTIME_PRECISION;
65 }
66
67 /* Return the number of seconds in T.  */
68 XTIME_INLINE xtime_t
69 xtime_sec (xtime_t t)
70 {
71   return (XTIME_PRECISION == 1
72           ? t
73           : t < 0
74           ? (t + XTIME_PRECISION - 1) / XTIME_PRECISION - 1
75           : xtime_nonnegative_sec (t));
76 }
77
78 /* Return the number of nanoseconds in T, which must be nonnegative.  */
79 XTIME_INLINE long int
80 xtime_nonnegative_nsec (xtime_t t)
81 {
82   return t % XTIME_PRECISION;
83 }
84
85 /* Return the number of nanoseconds in T.  */
86 XTIME_INLINE long int
87 xtime_nsec (xtime_t t)
88 {
89   long int ns = t % XTIME_PRECISION;
90   if (ns < 0)
91     ns += XTIME_PRECISION;
92   return ns;
93 }
94
95 #ifdef  __cplusplus
96 }
97 #endif
98
99 #endif