* modules/gethrxtime: New file.
[gnulib.git] / lib / xtime.h
1 /* xtime -- extended-resolution integer time stamps
2
3    Copyright (C) 2005 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
18
19 /* Written by Paul Eggert.  */
20
21 #ifndef XTIME_H_
22 #define XTIME_H_ 1
23
24 /* xtime_t is a signed type used for time stamps.  It is an integer
25    type that is a count of nanoseconds -- except for obsolescent hosts
26    without sufficiently-wide integers, where it is a count of
27    seconds.  */
28 #if HAVE_LONG_LONG
29 typedef long long int xtime_t;
30 # define XTIME_PRECISION 1000000000LL
31 #else
32 # include <limits.h>
33 typedef long int xtime_t;
34 # if LONG_MAX >> 31 >> 31 == 0
35 #  define XTIME_PRECISION 1L
36 # else
37 #  define XTIME_PRECISION 1000000000L
38 # endif
39 #endif
40
41 /* Return an extended time value that contains S seconds and NS
42    nanoseconds, without any overflow checking.  */
43 static inline xtime_t
44 xtime_make (xtime_t s, int ns)
45 {
46   if (XTIME_PRECISION == 1)
47     return s;
48   else
49     return XTIME_PRECISION * s + ns;
50 }
51
52 /* Return the number of seconds in T, which must be nonnegative.  */
53 static inline xtime_t
54 xtime_nonnegative_sec (xtime_t t)
55 {
56   return t / XTIME_PRECISION;
57 }
58
59 /* Return the number of seconds in T.  */
60 static inline xtime_t
61 xtime_sec (xtime_t t)
62 {
63   return (XTIME_PRECISION == 1
64           ? t
65           : t < 0
66           ? (t + XTIME_PRECISION - 1) / XTIME_PRECISION - 1
67           : xtime_nonnegative_sec (t));
68 }
69
70 /* Return the number of nanoseconds in T, which must be nonnegative.  */
71 static inline int
72 xtime_nonnegative_nsec (xtime_t t)
73 {
74   return t % XTIME_PRECISION;
75 }
76
77 /* Return the number of nanoseconds in T.  */
78 static inline int
79 xtime_nsec (xtime_t t)
80 {
81   int ns = t % XTIME_PRECISION;
82   if (ns < 0)
83     ns += XTIME_PRECISION;
84   return ns;
85 }
86
87 #endif