1 // The _PyTime_t API is written to use timestamp and timeout values stored in
2 // various formats and to read clocks.
3 //
4 // The _PyTime_t type is an integer to support directly common arithmetic
5 // operations like t1 + t2.
6 //
7 // The _PyTime_t API supports a resolution of 1 nanosecond. The _PyTime_t type
8 // is signed to support negative timestamps. The supported range is around
9 // [-292.3 years; +292.3 years]. Using the Unix epoch (January 1st, 1970), the
10 // supported date range is around [1677-09-21; 2262-04-11].
11 //
12 // Formats:
13 //
14 // * seconds
15 // * seconds as a floating pointer number (C double)
16 // * milliseconds (10^-3 seconds)
17 // * microseconds (10^-6 seconds)
18 // * 100 nanoseconds (10^-7 seconds)
19 // * nanoseconds (10^-9 seconds)
20 // * timeval structure, 1 microsecond resolution (10^-6 seconds)
21 // * timespec structure, 1 nanosecond resolution (10^-9 seconds)
22 //
23 // Integer overflows are detected and raise OverflowError. Conversion to a
24 // resolution worse than 1 nanosecond is rounded correctly with the requested
25 // rounding mode. There are 4 rounding modes: floor (towards -inf), ceiling
26 // (towards +inf), half even and up (away from zero).
27 //
28 // Some functions clamp the result in the range [_PyTime_MIN; _PyTime_MAX], so
29 // the caller doesn't have to handle errors and doesn't need to hold the GIL.
30 // For example, _PyTime_Add(t1, t2) computes t1+t2 and clamp the result on
31 // overflow.
32 //
33 // Clocks:
34 //
35 // * System clock
36 // * Monotonic clock
37 // * Performance counter
38 //
39 // Operations like (t * k / q) with integers are implemented in a way to reduce
40 // the risk of integer overflow. Such operation is used to convert a clock
41 // value expressed in ticks with a frequency to _PyTime_t, like
42 // QueryPerformanceCounter() with QueryPerformanceFrequency().
43 
44 #ifndef Py_LIMITED_API
45 #ifndef Py_PYTIME_H
46 #define Py_PYTIME_H
47 
48 /**************************************************************************
49 Symbols and macros to supply platform-independent interfaces to time related
50 functions and constants
51 **************************************************************************/
52 #ifdef __cplusplus
53 extern "C" {
54 #endif
55 
56 /* _PyTime_t: Python timestamp with subsecond precision. It can be used to
57    store a duration, and so indirectly a date (related to another date, like
58    UNIX epoch). */
59 typedef int64_t _PyTime_t;
60 // _PyTime_MIN nanoseconds is around -292.3 years
61 #define _PyTime_MIN INT64_MIN
62 // _PyTime_MAX nanoseconds is around +292.3 years
63 #define _PyTime_MAX INT64_MAX
64 #define _SIZEOF_PYTIME_T 8
65 
66 typedef enum {
67     /* Round towards minus infinity (-inf).
68        For example, used to read a clock. */
69     _PyTime_ROUND_FLOOR=0,
70     /* Round towards infinity (+inf).
71        For example, used for timeout to wait "at least" N seconds. */
72     _PyTime_ROUND_CEILING=1,
73     /* Round to nearest with ties going to nearest even integer.
74        For example, used to round from a Python float. */
75     _PyTime_ROUND_HALF_EVEN=2,
76     /* Round away from zero
77        For example, used for timeout. _PyTime_ROUND_CEILING rounds
78        -1e-9 to 0 milliseconds which causes bpo-31786 issue.
79        _PyTime_ROUND_UP rounds -1e-9 to -1 millisecond which keeps
80        the timeout sign as expected. select.poll(timeout) must block
81        for negative values." */
82     _PyTime_ROUND_UP=3,
83     /* _PyTime_ROUND_TIMEOUT (an alias for _PyTime_ROUND_UP) should be
84        used for timeouts. */
85     _PyTime_ROUND_TIMEOUT = _PyTime_ROUND_UP
86 } _PyTime_round_t;
87 
88 
89 /* Convert a time_t to a PyLong. */
90 PyAPI_FUNC(PyObject *) _PyLong_FromTime_t(
91     time_t sec);
92 
93 /* Convert a PyLong to a time_t. */
94 PyAPI_FUNC(time_t) _PyLong_AsTime_t(
95     PyObject *obj);
96 
97 /* Convert a number of seconds, int or float, to time_t. */
98 PyAPI_FUNC(int) _PyTime_ObjectToTime_t(
99     PyObject *obj,
100     time_t *sec,
101     _PyTime_round_t);
102 
103 /* Convert a number of seconds, int or float, to a timeval structure.
104    usec is in the range [0; 999999] and rounded towards zero.
105    For example, -1.2 is converted to (-2, 800000). */
106 PyAPI_FUNC(int) _PyTime_ObjectToTimeval(
107     PyObject *obj,
108     time_t *sec,
109     long *usec,
110     _PyTime_round_t);
111 
112 /* Convert a number of seconds, int or float, to a timespec structure.
113    nsec is in the range [0; 999999999] and rounded towards zero.
114    For example, -1.2 is converted to (-2, 800000000). */
115 PyAPI_FUNC(int) _PyTime_ObjectToTimespec(
116     PyObject *obj,
117     time_t *sec,
118     long *nsec,
119     _PyTime_round_t);
120 
121 
122 /* Create a timestamp from a number of seconds. */
123 PyAPI_FUNC(_PyTime_t) _PyTime_FromSeconds(int seconds);
124 
125 /* Macro to create a timestamp from a number of seconds, no integer overflow.
126    Only use the macro for small values, prefer _PyTime_FromSeconds(). */
127 #define _PYTIME_FROMSECONDS(seconds) \
128             ((_PyTime_t)(seconds) * (1000 * 1000 * 1000))
129 
130 /* Create a timestamp from a number of nanoseconds. */
131 PyAPI_FUNC(_PyTime_t) _PyTime_FromNanoseconds(_PyTime_t ns);
132 
133 /* Create a timestamp from nanoseconds (Python int). */
134 PyAPI_FUNC(int) _PyTime_FromNanosecondsObject(_PyTime_t *t,
135     PyObject *obj);
136 
137 /* Convert a number of seconds (Python float or int) to a timestamp.
138    Raise an exception and return -1 on error, return 0 on success. */
139 PyAPI_FUNC(int) _PyTime_FromSecondsObject(_PyTime_t *t,
140     PyObject *obj,
141     _PyTime_round_t round);
142 
143 /* Convert a number of milliseconds (Python float or int, 10^-3) to a timestamp.
144    Raise an exception and return -1 on error, return 0 on success. */
145 PyAPI_FUNC(int) _PyTime_FromMillisecondsObject(_PyTime_t *t,
146     PyObject *obj,
147     _PyTime_round_t round);
148 
149 /* Convert a timestamp to a number of seconds as a C double. */
150 PyAPI_FUNC(double) _PyTime_AsSecondsDouble(_PyTime_t t);
151 
152 /* Convert timestamp to a number of milliseconds (10^-3 seconds). */
153 PyAPI_FUNC(_PyTime_t) _PyTime_AsMilliseconds(_PyTime_t t,
154     _PyTime_round_t round);
155 
156 /* Convert timestamp to a number of microseconds (10^-6 seconds). */
157 PyAPI_FUNC(_PyTime_t) _PyTime_AsMicroseconds(_PyTime_t t,
158     _PyTime_round_t round);
159 
160 /* Convert timestamp to a number of nanoseconds (10^-9 seconds). */
161 PyAPI_FUNC(_PyTime_t) _PyTime_AsNanoseconds(_PyTime_t t);
162 
163 #ifdef MS_WINDOWS
164 // Convert timestamp to a number of 100 nanoseconds (10^-7 seconds).
165 PyAPI_FUNC(_PyTime_t) _PyTime_As100Nanoseconds(_PyTime_t t,
166     _PyTime_round_t round);
167 #endif
168 
169 /* Convert timestamp to a number of nanoseconds (10^-9 seconds) as a Python int
170    object. */
171 PyAPI_FUNC(PyObject *) _PyTime_AsNanosecondsObject(_PyTime_t t);
172 
173 #ifndef MS_WINDOWS
174 /* Create a timestamp from a timeval structure.
175    Raise an exception and return -1 on overflow, return 0 on success. */
176 PyAPI_FUNC(int) _PyTime_FromTimeval(_PyTime_t *tp, struct timeval *tv);
177 #endif
178 
179 /* Convert a timestamp to a timeval structure (microsecond resolution).
180    tv_usec is always positive.
181    Raise an exception and return -1 if the conversion overflowed,
182    return 0 on success. */
183 PyAPI_FUNC(int) _PyTime_AsTimeval(_PyTime_t t,
184     struct timeval *tv,
185     _PyTime_round_t round);
186 
187 /* Similar to _PyTime_AsTimeval() but don't raise an exception on overflow.
188    On overflow, clamp tv_sec to _PyTime_t min/max. */
189 PyAPI_FUNC(void) _PyTime_AsTimeval_clamp(_PyTime_t t,
190     struct timeval *tv,
191     _PyTime_round_t round);
192 
193 /* Convert a timestamp to a number of seconds (secs) and microseconds (us).
194    us is always positive. This function is similar to _PyTime_AsTimeval()
195    except that secs is always a time_t type, whereas the timeval structure
196    uses a C long for tv_sec on Windows.
197    Raise an exception and return -1 if the conversion overflowed,
198    return 0 on success. */
199 PyAPI_FUNC(int) _PyTime_AsTimevalTime_t(
200     _PyTime_t t,
201     time_t *secs,
202     int *us,
203     _PyTime_round_t round);
204 
205 #if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_KQUEUE)
206 /* Create a timestamp from a timespec structure.
207    Raise an exception and return -1 on overflow, return 0 on success. */
208 PyAPI_FUNC(int) _PyTime_FromTimespec(_PyTime_t *tp, struct timespec *ts);
209 
210 /* Convert a timestamp to a timespec structure (nanosecond resolution).
211    tv_nsec is always positive.
212    Raise an exception and return -1 on error, return 0 on success. */
213 PyAPI_FUNC(int) _PyTime_AsTimespec(_PyTime_t t, struct timespec *ts);
214 
215 /* Similar to _PyTime_AsTimespec() but don't raise an exception on overflow.
216    On overflow, clamp tv_sec to _PyTime_t min/max. */
217 PyAPI_FUNC(void) _PyTime_AsTimespec_clamp(_PyTime_t t, struct timespec *ts);
218 #endif
219 
220 
221 // Compute t1 + t2. Clamp to [_PyTime_MIN; _PyTime_MAX] on overflow.
222 PyAPI_FUNC(_PyTime_t) _PyTime_Add(_PyTime_t t1, _PyTime_t t2);
223 
224 /* Compute ticks * mul / div.
225    Clamp to [_PyTime_MIN; _PyTime_MAX] on overflow.
226    The caller must ensure that ((div - 1) * mul) cannot overflow. */
227 PyAPI_FUNC(_PyTime_t) _PyTime_MulDiv(_PyTime_t ticks,
228     _PyTime_t mul,
229     _PyTime_t div);
230 
231 /* Structure used by time.get_clock_info() */
232 typedef struct {
233     const char *implementation;
234     int monotonic;
235     int adjustable;
236     double resolution;
237 } _Py_clock_info_t;
238 
239 /* Get the current time from the system clock.
240 
241    If the internal clock fails, silently ignore the error and return 0.
242    On integer overflow, silently ignore the overflow and clamp the clock to
243    [_PyTime_MIN; _PyTime_MAX].
244 
245    Use _PyTime_GetSystemClockWithInfo() to check for failure. */
246 PyAPI_FUNC(_PyTime_t) _PyTime_GetSystemClock(void);
247 
248 /* Get the current time from the system clock.
249  * On success, set *t and *info (if not NULL), and return 0.
250  * On error, raise an exception and return -1.
251  */
252 PyAPI_FUNC(int) _PyTime_GetSystemClockWithInfo(
253     _PyTime_t *t,
254     _Py_clock_info_t *info);
255 
256 /* Get the time of a monotonic clock, i.e. a clock that cannot go backwards.
257    The clock is not affected by system clock updates. The reference point of
258    the returned value is undefined, so that only the difference between the
259    results of consecutive calls is valid.
260 
261    If the internal clock fails, silently ignore the error and return 0.
262    On integer overflow, silently ignore the overflow and clamp the clock to
263    [_PyTime_MIN; _PyTime_MAX].
264 
265    Use _PyTime_GetMonotonicClockWithInfo() to check for failure. */
266 PyAPI_FUNC(_PyTime_t) _PyTime_GetMonotonicClock(void);
267 
268 /* Get the time of a monotonic clock, i.e. a clock that cannot go backwards.
269    The clock is not affected by system clock updates. The reference point of
270    the returned value is undefined, so that only the difference between the
271    results of consecutive calls is valid.
272 
273    Fill info (if set) with information of the function used to get the time.
274 
275    Return 0 on success, raise an exception and return -1 on error. */
276 PyAPI_FUNC(int) _PyTime_GetMonotonicClockWithInfo(
277     _PyTime_t *t,
278     _Py_clock_info_t *info);
279 
280 
281 /* Converts a timestamp to the Gregorian time, using the local time zone.
282    Return 0 on success, raise an exception and return -1 on error. */
283 PyAPI_FUNC(int) _PyTime_localtime(time_t t, struct tm *tm);
284 
285 /* Converts a timestamp to the Gregorian time, assuming UTC.
286    Return 0 on success, raise an exception and return -1 on error. */
287 PyAPI_FUNC(int) _PyTime_gmtime(time_t t, struct tm *tm);
288 
289 /* Get the performance counter: clock with the highest available resolution to
290    measure a short duration.
291 
292    If the internal clock fails, silently ignore the error and return 0.
293    On integer overflow, silently ignore the overflow and clamp the clock to
294    [_PyTime_MIN; _PyTime_MAX].
295 
296    Use _PyTime_GetPerfCounterWithInfo() to check for failure. */
297 PyAPI_FUNC(_PyTime_t) _PyTime_GetPerfCounter(void);
298 
299 /* Get the performance counter: clock with the highest available resolution to
300    measure a short duration.
301 
302    Fill info (if set) with information of the function used to get the time.
303 
304    Return 0 on success, raise an exception and return -1 on error. */
305 PyAPI_FUNC(int) _PyTime_GetPerfCounterWithInfo(
306     _PyTime_t *t,
307     _Py_clock_info_t *info);
308 
309 
310 // Create a deadline.
311 // Pseudo code: _PyTime_GetMonotonicClock() + timeout.
312 PyAPI_FUNC(_PyTime_t) _PyDeadline_Init(_PyTime_t timeout);
313 
314 // Get remaining time from a deadline.
315 // Pseudo code: deadline - _PyTime_GetMonotonicClock().
316 PyAPI_FUNC(_PyTime_t) _PyDeadline_Get(_PyTime_t deadline);
317 
318 #ifdef __cplusplus
319 }
320 #endif
321 
322 #endif /* Py_PYTIME_H */
323 #endif /* Py_LIMITED_API */
324