Debian Codegraph @

pypy/module/time/interp_time.py

raw symbols SCIP
1 from rpython.rtyper.tool import rffi_platform as platform
2 from rpython.rtyper.lltypesystem import rffi
3 from pypy.interpreter.error import (OperationError, oefmt,
4 strerror as _strerror, exception_from_saved_errno)
5 from pypy.interpreter.gateway import unwrap_spec
6 from pypy.module.time.timeutils import (
7 SECS_TO_NS, MS_TO_NS, US_TO_NS, timestamp_w)
8 from pypy.interpreter.unicodehelper import decode_utf8sp
9 from pypy.module._codecs.locale import (
10 str_decode_locale_surrogateescape, utf8_encode_locale_surrogateescape)
11 from pypy import pypydir
12 from rpython.rtyper.lltypesystem import lltype
13 from rpython.rlib.rarithmetic import (
14 intmask, r_ulonglong, r_longfloat, r_int64, widen, ovfcheck,
15 ovfcheck_float_to_int, INT_MIN, r_uint, r_longlong)
16 from rpython.rlib.rtime import (TIMEVAL,
17 HAVE_GETTIMEOFDAY, HAVE_FTIME)
18 from rpython.rlib import rposix, rtime
19 from rpython.translator.tool.cbuild import ExternalCompilationInfo
20 from rpython.rlib.objectmodel import we_are_translated
21 from rpython.tool.cparser import CTypeSpace
22 from rpython.translator import cdir
23
24 import errno
25 import os
26 import math
27 import sys
28 import time as pytime
29
30 src_dir = os.path.join(pypydir, 'module', 'cpyext', 'src')
31 my_dir = os.path.join(pypydir, 'module', 'time', 'src')
32
33 if HAVE_FTIME:
34 from rpython.rlib.rtime import TIMEB, c_ftime
35
36 _POSIX = os.name == "posix"
37 _WIN = os.name == "nt"
38 _MACOSX = sys.platform == "darwin"
39 _CYGWIN = sys.platform == "cygwin"
40
41 _time_zones = []
42 if _CYGWIN:
43 _time_zones = ["GMT-12", "GMT-11", "GMT-10", "GMT-9", "GMT-8", "GMT-7",
44 "GMT-6", "GMT-5", "GMT-4", "GMT-3", "GMT-2", "GMT-1",
45 "GMT", "GMT+1", "GMT+2", "GMT+3", "GMT+4", "GMT+5",
46 "GMT+6", "GMT+7", "GMT+8", "GMT+9", "GMT+10", "GMT+11",
47 "GMT+12", "GMT+13", "GMT+14"]
48
49
50 if r_uint.BITS == 64:
51 tolong = intmask
52 else:
53 tolong = r_int64
54
55 if _WIN:
56 # Interruptible sleeps on Windows:
57 # We install a specific Console Ctrl Handler which sets an 'event'.
58 # time.sleep() will actually call WaitForSingleObject with the desired
59 # timeout. On Ctrl-C, the signal handler is called, the event is set,
60 # and the wait function exits.
61 from rpython.rlib import rwin32
62 from pypy.interpreter.error import wrap_oserror
63 from rpython.rlib import rthread as thread
64
65 wineci = ExternalCompilationInfo(
66 includes = ['windows.h'],
67 post_include_bits = [
68 "RPY_EXTERN\n"
69 "BOOL pypy_timemodule_setCtrlHandler(HANDLE event);\n"
70 "RPY_EXTERN ULONGLONG pypy_GetTickCount64(FARPROC address);"
71 ],
72 separate_module_sources=['''
73 /* this 'extern' is defined in translator/c/src/signals.c */
74 #ifdef PYPY_SIGINT_INTERRUPT_EVENT
75 extern HANDLE pypy_sigint_interrupt_event;
76 #endif
77
78 static BOOL WINAPI CtrlHandlerRoutine(
79 DWORD dwCtrlType)
80 {
81 return TRUE; /* like CPython 3.6 */
82 }
83
84 BOOL pypy_timemodule_setCtrlHandler(HANDLE event)
85 {
86 #ifdef PYPY_SIGINT_INTERRUPT_EVENT
87 pypy_sigint_interrupt_event = event;
88 #endif
89 return SetConsoleCtrlHandler(CtrlHandlerRoutine, TRUE);
90 }
91
92 ULONGLONG pypy_GetTickCount64(FARPROC address) {
93 ULONGLONG (WINAPI *func)();
94 *(FARPROC*)&func = address;
95 return func();
96 }
97
98 '''],
99 )
100 _setCtrlHandlerRoutine = rffi.llexternal(
101 'pypy_timemodule_setCtrlHandler',
102 [rwin32.HANDLE], rwin32.BOOL,
103 compilation_info=wineci,
104 save_err=rffi.RFFI_SAVE_LASTERROR)
105
106 pypy_GetTickCount64 = rffi.llexternal(
107 'pypy_GetTickCount64',
108 [rffi.VOIDP],
109 rffi.ULONGLONG, compilation_info=wineci)
110
111 class GlobalState:
112 def __init__(self):
113 self.init()
114
115 def init(self):
116 self.interrupt_event = rwin32.NULL_HANDLE
117
118 def startup(self, space):
119 # Initialize the event handle used to signal Ctrl-C
120 try:
121 globalState.interrupt_event = rwin32.CreateEvent(
122 rffi.NULL, True, False, rffi.NULL)
123 except WindowsError as e:
124 raise wrap_oserror(space, e)
125 if not _setCtrlHandlerRoutine(globalState.interrupt_event):
126 raise wrap_oserror(space,
127 rwin32.lastSavedWindowsError("SetConsoleCtrlHandler"))
128
129 globalState = GlobalState()
130
131 class State:
132 def __init__(self, space):
133 self.main_thread = 0
134
135 def _cleanup_(self):
136 self.main_thread = 0
137 globalState.init()
138
139 def startup(self, space):
140 self.main_thread = thread.get_ident()
141 globalState.startup(space)
142
143 def get_interrupt_event(self):
144 return globalState.interrupt_event
145
146 class TimeState(object):
147 GetTickCount64_handle = lltype.nullptr(rffi.VOIDP.TO)
148 def __init__(self):
149 self.n_overflow = 0
150 self.last_ticks = 0
151 self.divisor = 0
152 self.counter_start = 0
153
154 def check_GetTickCount64(self, *args):
155 if (self.GetTickCount64_handle !=
156 lltype.nullptr(rffi.VOIDP.TO)):
157 return True
158 from rpython.rlib.rdynload import GetModuleHandle, dlsym
159 hKernel32 = GetModuleHandle("KERNEL32")
160 try:
161 GetTickCount64_handle = dlsym(hKernel32, 'GetTickCount64')
162 except KeyError:
163 return False
164 self.GetTickCount64_handle = GetTickCount64_handle
165 return True
166
167 def GetTickCount64(self, *args):
168 assert (self.GetTickCount64_handle !=
169 lltype.nullptr(rffi.VOIDP.TO))
170 return pypy_GetTickCount64(
171 self.GetTickCount64_handle, *args)
172
173 time_state = TimeState()
174
175 cts = CTypeSpace()
176 with open(os.path.join(my_dir, 'time_module.h')) as fid:
177 data = fid.read()
178 start = data.find("// parse from here")
179 stop = data.find("// stop parsing")
180 src = data[start:stop]
181 cts.parse_source(src)
182
183 compile_extra = ["-DBUILD_TIME_MODULE", "-DHAVE_CLOCK_GETTIME"]
184 _includes = ["time.h", os.path.join(my_dir, "time_module.h")]
185 compile_extra.append("-DSIZEOF_TIME_T=%d" % rffi.sizeof(rffi.TIME_T))
186 compile_extra.append("-DSIZEOF_LONG_LONG=%d" % rffi.sizeof(rffi.LONGLONG))
187 compile_extra.append("-DSIZEOF_LONG=%d" % rffi.sizeof(rffi.LONG))
188 if _POSIX:
189 _includes.append('sys/time.h')
190 _includes.append(os.path.join(my_dir, "time_module_posix.h"))
191 compile_extra.append("-DHAVE_SYS_TIME_H")
192 if _MACOSX:
193 _includes.append('mach/mach_time.h')
194 compile_extra.append("-DHAVE_SYS_TIME_H")
195 if _WIN:
196 compile_extra.append("-DMS_WINDOWS")
197
198 HAS_CLOCK_HIGHRES = rtime.CLOCK_HIGHRES is not None
199 separate_module_sources = []
200 if HAS_CLOCK_HIGHRES:
201 compile_extra.append("-DCLOCK_HIGHRES")
202
203 if rtime.HAVE_NANOSLEEP:
204 compile_extra.append("-DHAVE_NANOSLEEP")
205 separate_module_sources.append("""
206 #include <errno.h>
207 RPY_EXTERN int
208 py_nanosleep(const struct timespec *rqtp, struct timespec *rmtp);
209
210 RPY_EXTERN int
211 py_nanosleep(const struct timespec *rqtp, struct timespec *rmtp)
212 {
213 int ret = nanosleep(rqtp, rmtp);
214 if (ret == 0)
215 return 0;
216 return errno;
217 }
218 """)
219
220 if rtime.HAVE_CLOCK_NANOSLEEP:
221 compile_extra.append("-DHAVE_CLOCK_NANOSLEEP")
222 separate_module_sources.append("""
223 #include <errno.h>
224
225 RPY_EXTERN int
226 py_clock_nanosleep(clockid_t clockid, int flags,
227 const struct timespec *request,
228 struct timespec *remain);
229 RPY_EXTERN int
230 py_clock_nanosleep(clockid_t clockid, int flags,
231 const struct timespec *request,
232 struct timespec *remain)
233 {
234 int ret = clock_nanosleep(clockid, flags, request, remain);
235 if (ret == 0)
236 return 0;
237 errno = ret;
238 return ret;
239 }
240 """)
241
242 class CConfig:
243 _compilation_info_ = ExternalCompilationInfo(
244 includes=_includes,
245 include_dirs = [my_dir, cdir],
246 libraries=rtime.libraries,
247 separate_module_files=[os.path.join(src_dir, "pytime.c")],
248 separate_module_sources=separate_module_sources,
249 compile_extra=compile_extra,
250 )
251 CLOCKS_PER_SEC = platform.ConstantInteger("CLOCKS_PER_SEC")
252
253 HAS_TM_ZONE = False
254
255 clock_info_t = cts.gettype("_Py_clock_info_t")
256 _PyTime_ROUND_CEILING = cts.definitions['_PyTime_round_t']._PyTime_ROUND_CEILING
257 if _POSIX:
258 calling_conv = 'c'
259 CConfig.timeval = platform.Struct("struct timeval",
260 [("tv_sec", rffi.INT),
261 ("tv_usec", rffi.INT)])
262 if _CYGWIN:
263 CConfig.tm = platform.Struct("struct tm", [("tm_sec", rffi.INT),
264 ("tm_min", rffi.INT), ("tm_hour", rffi.INT), ("tm_mday", rffi.INT),
265 ("tm_mon", rffi.INT), ("tm_year", rffi.INT), ("tm_wday", rffi.INT),
266 ("tm_yday", rffi.INT), ("tm_isdst", rffi.INT)])
267 else:
268 CConfig.tm = platform.Struct("struct tm", [("tm_sec", rffi.INT),
269 ("tm_min", rffi.INT), ("tm_hour", rffi.INT), ("tm_mday", rffi.INT),
270 ("tm_mon", rffi.INT), ("tm_year", rffi.INT), ("tm_wday", rffi.INT),
271 ("tm_yday", rffi.INT), ("tm_isdst", rffi.INT), ("tm_gmtoff", rffi.LONG),
272 ("tm_zone", rffi.CCHARP)])
273
274 HAS_TM_ZONE = True
275
276 elif _WIN:
277 calling_conv = 'win'
278 CConfig.tm = platform.Struct("struct tm", [("tm_sec", rffi.INT),
279 ("tm_min", rffi.INT), ("tm_hour", rffi.INT), ("tm_mday", rffi.INT),
280 ("tm_mon", rffi.INT), ("tm_year", rffi.INT), ("tm_wday", rffi.INT),
281 ("tm_yday", rffi.INT), ("tm_isdst", rffi.INT)])
282
283 if _MACOSX:
284 CConfig.TIMEBASE_INFO = platform.Struct("struct mach_timebase_info", [
285 ("numer", rffi.UINT),
286 ("denom", rffi.UINT),
287 ])
288
289 # XXX: optionally support the 2 additional tz fields
290 _STRUCT_TM_ITEMS = 9
291 if HAS_TM_ZONE:
292 _STRUCT_TM_ITEMS = 11
293
294 class cConfig:
295 pass
296
297 for k, v in platform.configure(CConfig).items():
298 setattr(cConfig, k, v)
299 cConfig.tm.__name__ = "_tm"
300
301 def external(name, args, result, eci=CConfig._compilation_info_, **kwds):
302 if _WIN and rffi.sizeof(rffi.TIME_T) == 8 and not name.startswith("_PyTime"):
303 # Recent Microsoft compilers use 64bit time_t and
304 # the corresponding functions are named differently
305 if (rffi.TIME_T in args or rffi.TIME_TP in args
306 or result in (rffi.TIME_T, rffi.TIME_TP)):
307 name = '_' + name + '64'
308 _calling_conv = kwds.pop('calling_conv', calling_conv)
309 releasegil = kwds.pop('releasegil', False)
310 return rffi.llexternal(name, args, result,
311 compilation_info=eci,
312 calling_conv=_calling_conv,
313 releasegil=releasegil,
314 **kwds)
315
316 if _POSIX:
317 cConfig.timeval.__name__ = "_timeval"
318 timeval = cConfig.timeval
319
320 CLOCKS_PER_SEC = cConfig.CLOCKS_PER_SEC
321 HAS_CLOCK_GETTIME_RUNTIME = rtime.HAS_CLOCK_GETTIME_RUNTIME
322 HAS_CLOCK_HIGHRES = rtime.CLOCK_HIGHRES is not None
323 HAS_CLOCK_MONOTONIC = rtime.CLOCK_MONOTONIC is not None
324 HAS_MONOTONIC = (_WIN or _MACOSX or
325 (HAS_CLOCK_GETTIME_RUNTIME and (HAS_CLOCK_HIGHRES or HAS_CLOCK_MONOTONIC)))
326 HAS_THREAD_TIME = (_WIN or
327 (HAS_CLOCK_GETTIME_RUNTIME and rtime.CLOCK_PROCESS_CPUTIME_ID is not None))
328 tm = cConfig.tm
329 pytime_t = rffi.LONGLONG # int64_t
330
331 glob_buf = lltype.malloc(tm, flavor='raw', zero=True, immortal=True)
332
333 _PyTime_GetPerfCounterWithInfo = external("_PyTime_GetPerfCounterWithInfo",
334 [rffi.CArrayPtr(pytime_t), rffi.CArrayPtr(clock_info_t)], rffi.INT)
335 _PyTime_GetMonotonicClockWithInfo = external("_PyTime_GetMonotonicClockWithInfo",
336 [rffi.CArrayPtr(pytime_t), rffi.CArrayPtr(clock_info_t)], rffi.INT)
337
338 _PyTime_GetSystemClockWithInfo = external("_PyTime_GetSystemClockWithInfo",
339 [rffi.CArrayPtr(pytime_t), rffi.CArrayPtr(clock_info_t)], rffi.INT)
340
341 _PyTime_AsSecondsDouble = external("_PyTime_AsSecondsDouble", [pytime_t], rffi.DOUBLE)
342
343 if _WIN:
344 _GetSystemTimeAsFileTime = rwin32.winexternal('GetSystemTimeAsFileTime',
345 [lltype.Ptr(rwin32.FILETIME)],
346 lltype.Void)
347 LPDWORD = rwin32.LPDWORD
348 _GetSystemTimeAdjustment = rwin32.winexternal(
349 'GetSystemTimeAdjustment',
350 [LPDWORD, LPDWORD, rwin32.LPBOOL],
351 rffi.INT)
352 def _gettimeofday_impl(space, w_info, return_ns):
353 with lltype.scoped_alloc(rwin32.FILETIME) as system_time:
354 _GetSystemTimeAsFileTime(system_time)
355 quad_part = (system_time.c_dwLowDateTime |
356 (r_ulonglong(system_time.c_dwHighDateTime) << 32))
357 # 11,644,473,600,000,000: number of microseconds between
358 # the 1st january 1601 and the 1st january 1970 (369 years + 80 leap
359 # days).
360
361 # We can't use that big number when translating for
362 # 32-bit system (which windows always is currently)
363 # XXX: Need to come up with a better solution
364 offset = (r_ulonglong(16384) * r_ulonglong(27) *
365 r_ulonglong(390625) * r_ulonglong(79) *
366 r_ulonglong(853) * r_ulonglong(10))
367 microseconds10x = quad_part - offset
368 if w_info:
369 with lltype.scoped_alloc(LPDWORD.TO, 1) as time_adjustment, \
370 lltype.scoped_alloc(LPDWORD.TO, 1) as time_increment, \
371 lltype.scoped_alloc(rwin32.LPBOOL.TO, 1) as is_time_adjustment_disabled:
372 _GetSystemTimeAdjustment(time_adjustment, time_increment,
373 is_time_adjustment_disabled)
374
375 _setinfo(space, w_info, "GetSystemTimeAsFileTime()",
376 intmask(time_increment[0]) * 1e-7, False, True)
377 if return_ns:
378 return space.newint(tolong(microseconds10x) * 10**2)
379 else:
380 return space.newfloat(float(tolong(microseconds10x)) / 1e7)
381 else:
382 if HAVE_GETTIMEOFDAY:
383 if rtime.GETTIMEOFDAY_NO_TZ:
384 c_gettimeofday = external('gettimeofday',
385 [lltype.Ptr(TIMEVAL)], rffi.INT)
386 else:
387 c_gettimeofday = external('gettimeofday',
388 [lltype.Ptr(TIMEVAL), rffi.VOIDP], rffi.INT)
389 def _gettimeofday_impl(space, w_info, return_ns):
390 if HAVE_GETTIMEOFDAY:
391 with lltype.scoped_alloc(TIMEVAL) as timeval:
392 if rtime.GETTIMEOFDAY_NO_TZ:
393 errcode = c_gettimeofday(timeval)
394 else:
395 void = lltype.nullptr(rffi.VOIDP.TO)
396 errcode = c_gettimeofday(timeval, void)
397 if rffi.cast(rffi.LONG, errcode) == 0:
398 if w_info is not None:
399 _setinfo(space, w_info, "gettimeofday()", 1e-6, False, True)
400 if return_ns:
401 return space.newint(
402 r_int64(timeval.c_tv_sec) * 10**9 +
403 r_int64(timeval.c_tv_usec) * 10**3)
404 else:
405 return space.newfloat(
406 widen(timeval.c_tv_sec) +
407 widen(timeval.c_tv_usec) * 1e-6)
408 if HAVE_FTIME:
409 with lltype.scoped_alloc(TIMEB) as t:
410 c_ftime(t)
411 if w_info is not None:
412 _setinfo(space, w_info, "ftime()", 1e-3, False, True)
413 if return_ns:
414 return space.newint(
415 r_int64(t.c_time) * 10**9 +
416 r_int64(intmask(t.c_millitm)) * 10**6)
417 else:
418 return space.newfloat(
419 widen(t.c_time) +
420 widen(t.c_millitm) * 1e-3)
421 else:
422 if w_info:
423 _setinfo(space, w_info, "time()", 1.0, False, True)
424 result = c_time(lltype.nullptr(rffi.TIME_TP.TO))
425 if return_ns:
426 return space.newint(r_int64(result) * 10**9)
427 else:
428 return space.newfloat(float(result))
429
430 def gettimeofday(space, w_info=None):
431 return _gettimeofday_impl(space, w_info, False)
432
433 _PyTime_AsTimeval = external("_PyTime_AsTimeval",
434 [pytime_t, lltype.Ptr(TIMEVAL), rffi.INT], rffi.INT)
435 TIMER_ABSTIME = 0x01 # from time.h on linux
436
437 TM_P = lltype.Ptr(tm)
438 c_time = external('time', [rffi.TIME_TP], rffi.TIME_T)
439 c_gmtime = external('gmtime', [rffi.TIME_TP], TM_P,
440 save_err=rffi.RFFI_SAVE_ERRNO)
441 c_mktime = external('mktime', [TM_P], rffi.TIME_T)
442 c_localtime = external('localtime', [rffi.TIME_TP], TM_P,
443 save_err=rffi.RFFI_SAVE_ERRNO)
444 if HAS_CLOCK_GETTIME_RUNTIME:
445 from rpython.rlib.rtime import TIMESPEC, c_clock_gettime
446 from rpython.rlib.rtime import c_clock_settime, c_clock_getres
447 _PyTime_AsTimespec = external("_PyTime_AsTimespec",
448 [pytime_t, lltype.Ptr(TIMESPEC)], rffi.INT)
449 if _POSIX:
450 c_tzset = external('tzset', [], lltype.Void)
451 if _WIN:
452 win_eci = ExternalCompilationInfo(
453 includes = ["time.h"],
454 post_include_bits = ["RPY_EXTERN "
455 "long pypy_get_timezone();\n"
456 "RPY_EXTERN "
457 "int pypy_get_daylight();\n"
458 "RPY_EXTERN "
459 "int pypy_get_tzname(size_t, int, char*);\n"
460 "RPY_EXTERN "
461 "void pypy__tzset();"],
462 separate_module_sources = ["""
463 long pypy_get_timezone() {
464 long timezone;
465 _get_timezone(&timezone);
466 return timezone;
467 };
468 int pypy_get_daylight() {
469 int daylight;
470 _get_daylight(&daylight);
471 return daylight;
472 };
473 int pypy_get_tzname(size_t len, int index, char * tzname) {
474 size_t s;
475 errno_t ret = _get_tzname(&s, tzname, len, index);
476 return (int)s;
477 };
478 void pypy__tzset() { _tzset(); }
479 """])
480 # Ensure sure that we use _tzset() and timezone from the same C Runtime.
481 c_tzset = external('pypy__tzset', [], lltype.Void, win_eci)
482 c_get_timezone = external('pypy_get_timezone', [], rffi.LONG, win_eci)
483 c_get_daylight = external('pypy_get_daylight', [], rffi.INT, win_eci)
484 c_get_tzname = external('pypy_get_tzname',
485 [rffi.SIZE_T, rffi.INT, rffi.CCHARP],
486 rffi.INT, win_eci, calling_conv='c')
487
488 if _WIN:
489 c_strftime = external('wcsftime',
490 [rffi.CWCHARP, rffi.SIZE_T, rffi.CWCHARP, TM_P],
491 rffi.SIZE_T,
492 save_err=rffi.RFFI_FULL_ERRNO_ZERO)
493 _CreateWaitableTimerExW = rwin32.winexternal('CreateWaitableTimerExW',
494 [rwin32.LPSECURITY_ATTRIBUTES, rwin32.LPCWSTR, rwin32.DWORD, rwin32.DWORD], rwin32.HANDLE)
495 _SetWaitableTimerEx = rwin32.winexternal('SetWaitableTimerEx',
496 [rwin32.HANDLE, rffi.CArrayPtr(rffi.LONGLONG), rffi.LONG, rffi.VOIDP, rffi.VOIDP, rffi.VOIDP, rffi.ULONG], rwin32.BOOL)
497 else:
498 c_strftime = external('strftime',
499 [rffi.CCHARP, rffi.SIZE_T, rffi.CCHARP, TM_P],
500 rffi.SIZE_T)
501
502 if rtime.HAVE_NANOSLEEP:
503 from rpython.rlib.rtime import TIMESPEC
504 nanosleep = external("py_nanosleep",
505 [lltype.Ptr(TIMESPEC), lltype.Ptr(TIMESPEC)],
506 rffi.INT, releasegil=True, save_err=rffi.RFFI_SAVE_ERRNO)
507 if rtime.HAVE_CLOCK_NANOSLEEP:
508 from rpython.rlib.rtime import TIMESPEC
509 clock_nanosleep = external("py_clock_nanosleep",
510 [rffi.INT, rffi.INT, lltype.Ptr(TIMESPEC), lltype.Ptr(TIMESPEC)], rffi.INT, releasegil=True, save_err=rffi.RFFI_SAVE_ERRNO)
511
512 def _init_timezone(space):
513 timezone = daylight = altzone = 0
514 tzname = ["", ""]
515
516 if _WIN:
517 c_tzset()
518 timezone = c_get_timezone()
519 altzone = timezone - 3600
520 daylight = c_get_daylight()
521 for i in [0, 1]:
522 blen = c_get_tzname(0, i, None)
523 with rffi.scoped_alloc_buffer(blen) as buf:
524 s = c_get_tzname(blen, i, buf.raw)
525 tzn = buf.str(s - 1)
526 tznutf8, _ = str_decode_locale_surrogateescape(tzn)
527 tzname[i] = tznutf8
528
529 if _POSIX:
530 if _CYGWIN:
531 YEAR = (365 * 24 + 6) * 3600
532
533 # about January 11th
534 t = (((c_time(lltype.nullptr(rffi.TIME_TP.TO))) / YEAR) * YEAR + 10 * 24 * 3600)
535 # we cannot have reference to stack variable, put it on the heap
536 t_ref = lltype.malloc(rffi.TIME_TP.TO, 1, flavor='raw')
537 t_ref[0] = rffi.cast(rffi.TIME_T, t)
538 p = c_localtime(t_ref)
539 q = c_gmtime(t_ref)
540 janzone = (p.c_tm_hour + 24 * p.c_tm_mday) - (q.c_tm_hour + 24 * q.c_tm_mday)
541 if janzone < -12:
542 janname = " "
543 elif janzone > 14:
544 janname = " "
545 else:
546 janname = _time_zones[janzone - 12]
547 janzone = janzone * 3600
548 # about July 11th
549 tt = t + YEAR / 2
550 t_ref[0] = rffi.cast(rffi.TIME_T, tt)
551 p = c_localtime(t_ref)
552 q = c_gmtime(t_ref)
553 julyzone = (p.c_tm_hour + 24 * p.c_tm_mday) - (q.c_tm_hour + 24 * q.c_tm_mday)
554 if julyzone < -12:
555 julyname = " "
556 elif julyzone > 14:
557 julyname = " "
558 else:
559 julyname = _time_zones[julyzone - 12]
560 julyzone = julyzone * 3600
561 lltype.free(t_ref, flavor='raw')
562
563 if janzone < julyzone:
564 # DST is reversed in the southern hemisphere
565 timezone = julyzone
566 altzone = janzone
567 daylight = int(janzone != julyzone)
568 tzname = [julyname, janname]
569 else:
570 timezone = janzone
571 altzone = julyzone
572 daylight = int(janzone != julyzone)
573 tzname = [janname, julyname]
574
575 else:
576 YEAR = (365 * 24 + 6) * 3600
577
578 t = (((c_time(lltype.nullptr(rffi.TIME_TP.TO))) / YEAR) * YEAR)
579 # we cannot have reference to stack variable, put it on the heap
580 t_ref = lltype.malloc(rffi.TIME_TP.TO, 1, flavor='raw')
581 t_ref[0] = rffi.cast(rffi.TIME_T, t)
582 p = c_localtime(t_ref)
583 janzone = -p.c_tm_gmtoff
584 tm_zone = rffi.charp2str(p.c_tm_zone)
585 janname = [" ", tm_zone][bool(tm_zone)]
586 tt = t + YEAR / 2
587 t_ref[0] = rffi.cast(rffi.TIME_T, tt)
588 p = c_localtime(t_ref)
589 lltype.free(t_ref, flavor='raw')
590 tm_zone = rffi.charp2str(p.c_tm_zone)
591 julyzone = -p.c_tm_gmtoff
592 julyname = [" ", tm_zone][bool(tm_zone)]
593
594 if janzone < julyzone:
595 # DST is reversed in the southern hemisphere
596 timezone = julyzone
597 altzone = janzone
598 daylight = int(janzone != julyzone)
599 tzname = [julyname, janname]
600 else:
601 timezone = janzone
602 altzone = julyzone
603 daylight = int(janzone != julyzone)
604 tzname = [janname, julyname]
605
606 _set_module_object(space, "timezone", space.newint(timezone))
607 _set_module_object(space, 'daylight', space.newint(daylight))
608 tzname_w = [space.newtext(tzname[0]),
609 space.newtext(tzname[1])]
610 _set_module_object(space, 'tzname', space.newtuple(tzname_w))
611 _set_module_object(space, 'altzone', space.newint(altzone))
612
613 def _get_error_msg():
614 errno = rposix.get_saved_errno()
615 return _strerror(errno)
616
617 from errno import EINTR
618 if not _WIN:
619 from rpython.rlib.rtime import c_select
620 from rpython.rlib import rwin32
621
622 def time_sleep(space, w_secs):
623 timeout = timestamp_w(space, w_secs)
624 if not (timeout >= 0):
625 raise oefmt(space.w_ValueError,
626 "sleep length must be non-negative")
627 deadline = _monotonic_impl(space, None) + timeout
628 timeout_abs = None
629 timeout_ts = None
630 timeout_tv = None
631 if _WIN:
632 timer = rffi.cast(rwin32.HANDLE, 0)
633 try:
634 if rtime.HAVE_CLOCK_NANOSLEEP:
635 timeout_abs = lltype.malloc(TIMESPEC, flavor='raw')
636 if _PyTime_AsTimespec(deadline, timeout_abs) < 0:
637 raise oefmt(space.w_OverflowError,
638 "timestamp out of range for platform time_t")
639 elif rtime.HAVE_NANOSLEEP:
640 timeout_ts = lltype.malloc(TIMESPEC, flavor='raw')
641 elif not _WIN:
642 timeout_tv = lltype.malloc(TIMEVAL, flavor ='raw')
643 while True:
644 # 'deadline' is reduced at the end of the loop, for the next iteration.
645 NULL = lltype.nullptr(rffi.VOIDP.TO)
646 if _WIN:
647 timeout_100ns = timeout // 100
648 if timeout_100ns == 0:
649 # A value of zero causes the thread to relinquish the remainder of its
650 # time slice to any other thread that is ready to run. If there are no
651 # other threads ready to run, the function returns immediately, and
652 # the thread continues execution.
653 rtime.Sleep(rffi.cast(rffi.ULONG, 0))
654 return
655 relative_timeout = rffi.cast(rffi.LONGLONG, -timeout_100ns)
656 timer_flags = 0x02 # CREATE_WAITABLE_TIMER_HIGH_RESOLUTION
657 all_access = 0x1F0003 # TIMER_ALL_ACCESS
658 timer = _CreateWaitableTimerExW(lltype.nullptr(rwin32.LPSECURITY_ATTRIBUTES.TO),
659 rffi.cast(rwin32.LPCWSTR, 0),
660 timer_flags, all_access)
661 if not timer:
662 raise exception_from_saved_errno(space, space.w_OSError)
663 assert timer is not None
664 with lltype.scoped_alloc(rffi.CArray(rffi.LONGLONG), 1) as rt:
665 rt[0] = relative_timeout
666 if not _SetWaitableTimerEx(timer, rt, 0, NULL, NULL, NULL, 0):
667 raise exception_from_saved_errno(space, space.w_OSError)
668
669 main_thread = space.fromcache(State).main_thread
670 interruptible = (main_thread == thread.get_ident())
671 if interruptible:
672 # Only the main thread can be interrupted
673 space.getexecutioncontext().checksignals()
674 interrupt_event = space.fromcache(State).get_interrupt_event()
675 rwin32.ResetEvent(interrupt_event)
676 rc = rwin32.WaitForMultipleObjects([interrupt_event, timer])
677 else:
678 rc = rwin32.WaitForSingleObject(timer, rwin32.INFINITE)
679 if rc == rwin32.WAIT_FAILED:
680 raise exception_from_saved_errno(space, space.w_OSError)
681 if rc == rwin32.WAIT_OBJECT_0:
682 break
683 else:
684 NULL_TS = lltype.nullptr(lltype.Ptr(TIMESPEC).TO)
685 if rtime.HAVE_CLOCK_NANOSLEEP:
686 ret = clock_nanosleep(rtime.CLOCK_MONOTONIC, TIMER_ABSTIME, timeout_abs, NULL_TS);
687 pass
688 elif rtime.HAVE_NANOSLEEP:
689 if _PyTime_AsTimespec(timeout, timeout_ts) < 0:
690 raise oefmt(space.w_OverflowError,
691 "timestamp out of range for platform time_t")
692 ret = nanosleep(timeout_ts, NULL_TS);
693 if ret == 0:
694 break
695 if ret != EINTR:
696 raise exception_from_saved_errno(space, space.w_OSError)
697 else:
698 if _PyTime_AsTimeval(timeout, timeout_tv, _PyTime_ROUND_CEILING) < 0:
699 raise oefmt(space.w_OverflowError,
700 "timestamp out of range for platform time_t")
701 ret = rffi.cast(rffi.LONG,
702 c_select(0, NULL, NULL, NULL, timeout_tv))
703 if ret == 0:
704 break # normal path
705 if ret != EINTR:
706 raise exception_from_saved_errno(space, space.w_OSError)
707 space.getexecutioncontext().checksignals()
708 timeout = deadline - _monotonic_impl(space, None) # retry
709 if timeout <= 0:
710 break
711 finally:
712 if timeout_abs:
713 lltype.free(timeout_abs, flavor='raw')
714 if timeout_ts:
715 lltype.free(timeout_ts, flavor='raw')
716 if timeout_tv:
717 lltype.free(timeout_tv, flavor='raw')
718 if _WIN and timer:
719 rwin32.CloseHandle(timer)
720
721
722 def _get_module_object(space, obj_name):
723 w_module = space.getbuiltinmodule('time')
724 w_obj = space.getattr(w_module, space.newtext(obj_name))
725 return w_obj
726
727
728 def _set_module_object(space, obj_name, w_obj_value):
729 w_module = space.getbuiltinmodule('time')
730 space.setattr(w_module, space.newtext(obj_name), w_obj_value)
731 # XXX find a more appropriate way to ensure the values are preserved
732 # across module reloading
733 from pypy.interpreter.mixedmodule import MixedModule
734 assert isinstance(w_module, MixedModule)
735 w_module.reset_lazy_initial_values()
736
737
738 def _get_inttime(space, w_seconds):
739 # w_seconds can be a wrapped None (it will be automatically wrapped
740 # in the callers, so we never get a real None here).
741 if space.is_none(w_seconds):
742 seconds = pytime.time()
743 else:
744 seconds = space.float_w(w_seconds)
745 if math.isnan(seconds):
746 raise oefmt(space.w_ValueError,
747 "Invalid value Nan (not a number)")
748 #
749 t = rffi.cast(rffi.TIME_T, seconds)
750 #
751 # Logic from CPython: How much info did we lose? We assume that
752 # time_t is an integral type. If we lost a second or more, the
753 # input doesn't fit in a time_t; call it an error.
754 diff = seconds - rffi.cast(lltype.Float, t)
755 if diff <= -1.0 or diff >= 1.0:
756 raise oefmt(space.w_OverflowError,
757 "timestamp out of range for platform time_t")
758 return t
759
760 def _tm_to_tuple(space, t, zone="UTC", offset=0):
761 time_tuple = [
762 space.newint(rffi.getintfield(t, 'c_tm_year') + 1900),
763 space.newint(rffi.getintfield(t, 'c_tm_mon') + 1), # want january == 1
764 space.newint(rffi.getintfield(t, 'c_tm_mday')),
765 space.newint(rffi.getintfield(t, 'c_tm_hour')),
766 space.newint(rffi.getintfield(t, 'c_tm_min')),
767 space.newint(rffi.getintfield(t, 'c_tm_sec')),
768 space.newint((rffi.getintfield(t, 'c_tm_wday') + 6) % 7), # want monday == 0
769 space.newint(rffi.getintfield(t, 'c_tm_yday') + 1), # want january, 1 == 1
770 space.newint(rffi.getintfield(t, 'c_tm_isdst'))]
771
772 if HAS_TM_ZONE:
773 # CPython calls PyUnicode_DecodeLocale here should we do the same?
774 tm_zone, lgt, pos = decode_utf8sp(space, rffi.charp2str(t.c_tm_zone))
775 extra = [space.newtext(tm_zone, lgt),
776 space.newint(rffi.getintfield(t, 'c_tm_gmtoff'))]
777 else:
778 extra = [space.newtext(zone), space.newint(offset)]
779 w_time_tuple = space.newtuple(time_tuple + extra)
780 w_struct_time = _get_module_object(space, 'struct_time')
781 w_obj = space.call_function(w_struct_time, w_time_tuple)
782 return w_obj
783
784 def _gettmarg(space, w_tup, allowNone=True):
785 if space.is_none(w_tup):
786 if not allowNone:
787 raise oefmt(space.w_TypeError, "tuple expected")
788 # default to the current local time
789 tt = rffi.cast(rffi.TIME_T, pytime.time())
790 t_ref = lltype.malloc(rffi.TIME_TP.TO, 1, flavor='raw')
791 t_ref[0] = tt
792 pbuf = c_localtime(t_ref)
793 rffi.setintfield(pbuf, "c_tm_year",
794 rffi.getintfield(pbuf, "c_tm_year") + 1900)
795 lltype.free(t_ref, flavor='raw')
796 if not pbuf:
797 raise OperationError(space.w_ValueError,
798 space.newtext(*_get_error_msg()))
799 return pbuf
800
801 tup_w = space.fixedview(w_tup)
802 if len(tup_w) < 9:
803 raise oefmt(space.w_TypeError,
804 "argument must be sequence of at least length 9, not %d",
805 len(tup_w))
806
807 y = space.c_int_w(tup_w[0])
808 tm_mon = space.c_int_w(tup_w[1])
809 if tm_mon == 0:
810 tm_mon = 1
811 tm_mday = space.c_int_w(tup_w[2])
812 if tm_mday == 0:
813 tm_mday = 1
814 tm_yday = space.c_int_w(tup_w[7])
815 if tm_yday == 0:
816 tm_yday = 1
817 rffi.setintfield(glob_buf, 'c_tm_mon', tm_mon)
818 rffi.setintfield(glob_buf, 'c_tm_mday', tm_mday)
819 rffi.setintfield(glob_buf, 'c_tm_hour', space.c_int_w(tup_w[3]))
820 rffi.setintfield(glob_buf, 'c_tm_min', space.c_int_w(tup_w[4]))
821 rffi.setintfield(glob_buf, 'c_tm_sec', space.c_int_w(tup_w[5]))
822 rffi.setintfield(glob_buf, 'c_tm_wday', space.c_int_w(tup_w[6]))
823 rffi.setintfield(glob_buf, 'c_tm_yday', tm_yday)
824 rffi.setintfield(glob_buf, 'c_tm_isdst', space.c_int_w(tup_w[8]))
825 #
826 if HAS_TM_ZONE :
827 old_tm_zone = glob_buf.c_tm_zone
828 glob_buf.c_tm_zone = lltype.nullptr(rffi.CCHARP.TO)
829 rffi.setintfield(glob_buf, 'c_tm_gmtoff', 0)
830 if len(tup_w) >= 10:
831 # NOTE this is not cleanly solved!
832 # it saves the string that is later deleted when this
833 # function is called again. A refactoring of this module
834 # could remove this
835 tm_zone = space.utf8_w(tup_w[9])
836 malloced_str = rffi.str2charp(tm_zone, track_allocation=False)
837 if old_tm_zone != lltype.nullptr(rffi.CCHARP.TO):
838 rffi.free_charp(old_tm_zone, track_allocation=False)
839 glob_buf.c_tm_zone = malloced_str
840 if len(tup_w) >= 11:
841 rffi.setintfield(glob_buf, 'c_tm_gmtoff', space.c_int_w(tup_w[10]))
842
843 if (y < INT_MIN + 1900):
844 raise oefmt(space.w_OverflowError, "year out of range")
845
846 # tm_wday does not need checking of its upper-bound since taking "%
847 # 7" in _gettmarg() automatically restricts the range.
848 if rffi.getintfield(glob_buf, 'c_tm_wday') < -1:
849 raise oefmt(space.w_ValueError, "day of week out of range")
850
851 rffi.setintfield(glob_buf, 'c_tm_year', y)
852 rffi.setintfield(glob_buf, 'c_tm_mon',
853 rffi.getintfield(glob_buf, 'c_tm_mon') - 1)
854 rffi.setintfield(glob_buf, 'c_tm_wday',
855 (rffi.getintfield(glob_buf, 'c_tm_wday') + 1) % 7)
856 rffi.setintfield(glob_buf, 'c_tm_yday',
857 rffi.getintfield(glob_buf, 'c_tm_yday') - 1)
858
859 return glob_buf
860
861 def _checktm(space, t_ref):
862 """Checks added to make sure strftime() and asctime() do not crash
863 Python by indexing blindly into some array for a textual
864 representation by some bad index (fixes bug #897625). No check for
865 year or wday since handled in _gettmarg()."""
866 if not 0 <= rffi.getintfield(t_ref, 'c_tm_mon') <= 11:
867 raise oefmt(space.w_ValueError, "month out of range")
868 if not 1 <= rffi.getintfield(t_ref, 'c_tm_mday') <= 31:
869 raise oefmt(space.w_ValueError, "day of month out of range")
870 if not 0 <= rffi.getintfield(t_ref, 'c_tm_hour') <= 23:
871 raise oefmt(space.w_ValueError, "hour out of range")
872 if not 0 <= rffi.getintfield(t_ref, 'c_tm_min') <= 59:
873 raise oefmt(space.w_ValueError, "minute out of range")
874 if not 0 <= rffi.getintfield(t_ref, 'c_tm_sec') <= 61:
875 raise oefmt(space.w_ValueError, "seconds out of range")
876 # tm_wday does not need checking: "% 7" in _gettmarg() automatically
877 # restricts the range
878 if not 0 <= rffi.getintfield(t_ref, 'c_tm_yday') <= 365:
879 raise oefmt(space.w_ValueError, "day of year out of range")
880
881 def _time_impl(space, w_info):
882 with lltype.scoped_alloc(rffi.CArray(pytime_t), 1) as t:
883 if w_info:
884 with lltype.scoped_alloc(rffi.CArray(clock_info_t), 1) as info:
885 res = _PyTime_GetSystemClockWithInfo(t, info)
886 implementation = rffi.constcharp2str(info[0].c_implementation)
887 resolution = info[0].c_resolution
888 mono = bool(widen(info[0].c_monotonic))
889 adjust = bool(widen(info[0].c_adjustable))
890 _setinfo(space, w_info, implementation, resolution, mono, adjust)
891 else:
892 res = _PyTime_GetSystemClockWithInfo(t, rffi.cast(rffi.CArrayPtr(clock_info_t), 0))
893 if res < 0:
894 raise oefmt(space.w_RuntimeError, "could not get system clock")
895 return widen(t[0])
896
897 def time_time(space):
898 """time() -> floating point number
899
900 Return the current time in seconds since the Epoch.
901 Fractions of a second may be present if the system clock provides them."""
902 t = _time_impl(space, None)
903 d = _PyTime_AsSecondsDouble(t)
904 return space.newfloat(d)
905
906 def time_time_ns(space):
907 """time_ns() -> int
908
909 Return the current time in nanoseconds since the Epoch."""
910 t = _time_impl(space, None)
911 return space.newint(t)
912
913 @unwrap_spec(name='text0')
914 def _get_time_info(space, name, w_info):
915 """_get_time_info(name, info) -> None
916 Internal helper for get_clock_info
917 """
918 if name == 'time':
919 _time_impl(space, w_info)
920 elif name == 'monotonic':
921 _monotonic_impl(space, w_info)
922 elif name == 'perf_counter':
923 _perf_counter_impl(space, w_info)
924 elif name == "process_time":
925 _process_time_impl(space, w_info, False)
926 elif name == "thread_time" and HAS_THREAD_TIME:
927 _thread_time_impl(space, w_info, False)
928 else:
929 raise oefmt(space.w_ValueError, "unknown clock")
930
931 def ctime(space, w_seconds=None):
932 """ctime([seconds]) -> string
933
934 Convert a time in seconds since the Epoch to a string in local time.
935 This is equivalent to asctime(localtime(seconds)). When the time tuple is
936 not present, current time as returned by localtime() is used."""
937
938 seconds = _get_inttime(space, w_seconds)
939 with lltype.scoped_alloc(rffi.TIME_TP.TO, 1) as t_ref:
940 t_ref[0] = seconds
941 p = c_localtime(t_ref)
942 if not p:
943 raise oefmt(space.w_OSError, "unconvertible time")
944 rffi.setintfield(p, "c_tm_year", rffi.getintfield(p, "c_tm_year") + 1900)
945 return _asctime(space, p)
946
947 # by now w_tup is an optional argument (and not *args)
948 # because of the ext. compiler bugs in handling such arguments (*args, **kwds)
949 def asctime(space, w_tup=None):
950 """asctime([tuple]) -> string
951
952 Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.
953 When the time tuple is not present, current time as returned by localtime()
954 is used."""
955 buf_value = _gettmarg(space, w_tup)
956 _checktm(space, buf_value)
957 return _asctime(space, buf_value)
958
959 _wday_names = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
960 _mon_names = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
961 "Oct", "Nov", "Dec"]
962
963 def _asctime(space, t_ref):
964 # Inspired by Open Group reference implementation available at
965 # http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html
966 getif = rffi.getintfield
967 args = [space.newtext(_wday_names[getif(t_ref, 'c_tm_wday')]),
968 space.newtext(_mon_names[getif(t_ref, 'c_tm_mon')]),
969 space.newint(getif(t_ref, 'c_tm_mday')),
970 space.newint(getif(t_ref, 'c_tm_hour')),
971 space.newint(getif(t_ref, 'c_tm_min')),
972 space.newint(getif(t_ref, 'c_tm_sec')),
973 space.newint(getif(t_ref, 'c_tm_year'))]
974 return space.mod(space.newtext("%.3s %.3s%3d %.2d:%.2d:%.2d %d"),
975 space.newtuple(args))
976
977 def gmtime(space, w_seconds=None):
978 """gmtime([seconds]) -> (tm_year, tm_mon, tm_day, tm_hour, tm_min,
979 tm_sec, tm_wday, tm_yday, tm_isdst)
980
981 Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.
982 GMT). When 'seconds' is not passed in, convert the current time instead.
983 """
984
985 # rpython does not support that a variable has two incompatible builtins
986 # as value so we have to duplicate the code. NOT GOOD! see localtime() too
987 seconds = _get_inttime(space, w_seconds)
988 with lltype.scoped_alloc(rffi.TIME_TP.TO, 1) as t_ref:
989 t_ref[0] = seconds
990 p = c_gmtime(t_ref)
991 if not p:
992 raise exception_from_saved_errno(space, space.w_OSError)
993 return _tm_to_tuple(space, p, zone="UTC", offset=0)
994
995 def localtime(space, w_seconds=None):
996 """localtime([seconds]) -> (tm_year, tm_mon, tm_day, tm_hour, tm_min,
997 tm_sec, tm_wday, tm_yday, tm_isdst)
998
999 Convert seconds since the Epoch to a time tuple expressing local time.
1000 When 'seconds' is not passed in, convert the current time instead."""
1001
1002 seconds = _get_inttime(space, w_seconds)
1003 with lltype.scoped_alloc(rffi.TIME_TP.TO, 1) as t_ref:
1004 t_ref[0] = seconds
1005 p = c_localtime(t_ref)
1006 if not p:
1007 raise exception_from_saved_errno(space, space.w_OSError)
1008 if HAS_TM_ZONE:
1009 return _tm_to_tuple(space, p)
1010 else:
1011 offset = space.int_w(_get_module_object(space, "timezone"))
1012 daylight_w = _get_module_object(space, 'daylight')
1013 tzname_w = _get_module_object(space, 'tzname')
1014 zone_w = space.getitem(tzname_w, daylight_w)
1015 if not space.eq_w(daylight_w, space.newint(0)):
1016 offset -= 3600
1017 return _tm_to_tuple(space, p, zone=space.utf8_w(zone_w), offset=-offset)
1018
1019
1020 def mktime(space, w_tup):
1021 """mktime(tuple) -> floating point number
1022
1023 Convert a time tuple in local time to seconds since the Epoch."""
1024
1025 buf = _gettmarg(space, w_tup, allowNone=False)
1026 rffi.setintfield(buf, "c_tm_wday", -1)
1027 rffi.setintfield(buf, "c_tm_year", rffi.getintfield(buf, "c_tm_year") - 1900)
1028 tt = c_mktime(buf)
1029 # A return value of -1 does not necessarily mean an error, but tm_wday
1030 # cannot remain set to -1 if mktime succeeds.
1031 if tt == -1 and rffi.getintfield(buf, "c_tm_wday") == -1:
1032 raise oefmt(space.w_OverflowError, "mktime argument out of range")
1033
1034 return space.newfloat(float(tt))
1035
1036 if HAS_CLOCK_GETTIME_RUNTIME:
1037 def _timespec_to_seconds(timespec):
1038 return widen(timespec.c_tv_sec) + widen(timespec.c_tv_nsec) * 1e-9
1039
1040 def _timespec_to_nanoseconds(timespec):
1041 return r_int64(timespec.c_tv_sec) * 10**9 + r_int64(timespec.c_tv_nsec)
1042
1043 def _clock_gettime_impl(space, clk_id, return_ns):
1044 with lltype.scoped_alloc(TIMESPEC) as timespec:
1045 ret = c_clock_gettime(clk_id, timespec)
1046 if ret != 0:
1047 raise exception_from_saved_errno(space, space.w_OSError)
1048 if return_ns:
1049 return space.newint(_timespec_to_nanoseconds(timespec))
1050 else:
1051 return space.newfloat(_timespec_to_seconds(timespec))
1052
1053 @unwrap_spec(clk_id='c_int')
1054 def clock_gettime(space, clk_id):
1055 """clock_gettime(clk_id) -> float
1056
1057 Return the time of the specified clock clk_id."""
1058 return _clock_gettime_impl(space, clk_id, False)
1059
1060 @unwrap_spec(clk_id='c_int')
1061 def clock_gettime_ns(space, clk_id):
1062 """clock_gettime_ns(clk_id) -> int
1063
1064 Return the time of the specified clock clk_id as nanoseconds."""
1065 return _clock_gettime_impl(space, clk_id, True)
1066
1067 @unwrap_spec(clk_id='c_int', secs=float)
1068 def clock_settime(space, clk_id, secs):
1069 """clock_settime(clk_id, time)
1070
1071 Set the time of the specified clock clk_id."""
1072 with lltype.scoped_alloc(TIMESPEC) as timespec:
1073 integer_secs = rffi.cast(TIMESPEC.c_tv_sec, secs)
1074 frac = secs - widen(integer_secs)
1075 rffi.setintfield(timespec, 'c_tv_sec', integer_secs)
1076 rffi.setintfield(timespec, 'c_tv_nsec', int(frac * 1e9))
1077 ret = c_clock_settime(clk_id, timespec)
1078 if ret != 0:
1079 raise exception_from_saved_errno(space, space.w_OSError)
1080
1081 @unwrap_spec(clk_id='c_int', ns=r_int64)
1082 def clock_settime_ns(space, clk_id, ns):
1083 """clock_settime_ns(clk_id, time)
1084
1085 Set the time of the specified clock clk_id with nanoseconds."""
1086 with lltype.scoped_alloc(TIMESPEC) as timespec:
1087 rffi.setintfield(timespec, 'c_tv_sec', ns // 10**9)
1088 rffi.setintfield(timespec, 'c_tv_nsec', ns % 10**9)
1089 ret = c_clock_settime(clk_id, timespec)
1090 if ret != 0:
1091 raise exception_from_saved_errno(space, space.w_OSError)
1092
1093 @unwrap_spec(clk_id='c_int')
1094 def clock_getres(space, clk_id):
1095 """clock_getres(clk_id) -> floating point number
1096
1097 Return the resolution (precision) of the specified clock clk_id."""
1098 with lltype.scoped_alloc(TIMESPEC) as timespec:
1099 ret = c_clock_getres(clk_id, timespec)
1100 if ret != 0:
1101 raise exception_from_saved_errno(space, space.w_OSError)
1102 secs = _timespec_to_seconds(timespec)
1103 return space.newfloat(secs)
1104
1105 if _POSIX:
1106 def tzset(space):
1107 """tzset()
1108
1109 Initialize, or reinitialize, the local timezone to the value stored in
1110 os.environ['TZ']. The TZ environment variable should be specified in
1111 standard Unix timezone format as documented in the tzset man page
1112 (eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently
1113 fall back to UTC. If the TZ environment variable is not set, the local
1114 timezone is set to the systems best guess of wallclock time.
1115 Changing the TZ environment variable without calling tzset *may* change
1116 the local timezone used by methods such as localtime, but this behaviour
1117 should not be relied on"""
1118
1119 c_tzset()
1120
1121 # reset timezone, altzone, daylight and tzname
1122 _init_timezone(space)
1123
1124 @unwrap_spec(format='text0')
1125 def strftime(space, format, w_tup=None):
1126 """strftime(format[, tuple]) -> string
1127
1128 Convert a time tuple to a string according to a format specification.
1129 See the library reference manual for formatting codes. When the time tuple
1130 is not present, current time as returned by localtime() is used."""
1131 from rpython.rlib.rutf8 import codepoints_in_utf8
1132 buf_value = _gettmarg(space, w_tup)
1133 _checktm(space, buf_value)
1134
1135 # Normalize tm_isdst just in case someone foolishly implements %Z
1136 # based on the assumption that tm_isdst falls within the range of
1137 # [-1, 1]
1138 if rffi.getintfield(buf_value, 'c_tm_isdst') < -1:
1139 rffi.setintfield(buf_value, 'c_tm_isdst', -1)
1140 elif rffi.getintfield(buf_value, 'c_tm_isdst') > 1:
1141 rffi.setintfield(buf_value, 'c_tm_isdst', 1)
1142 rffi.setintfield(buf_value, "c_tm_year",
1143 rffi.getintfield(buf_value, "c_tm_year") - 1900)
1144
1145 i = 1024
1146 passthrough = False
1147 if _WIN:
1148 tm_year = rffi.getintfield(buf_value, 'c_tm_year')
1149 if (tm_year + 1900 < 1 or 9999 < tm_year + 1900):
1150 raise oefmt(space.w_ValueError, "strftime() requires year in [1; 9999]")
1151
1152 # wcharp with track_allocation=True
1153 format_for_call = rffi.utf82wcharp(
1154 format, codepoints_in_utf8(format))
1155 else:
1156 try:
1157 format_for_call = utf8_encode_locale_surrogateescape(
1158 format, codepoints_in_utf8(format))
1159 except UnicodeEncodeError:
1160 format_for_call = format
1161 passthrough = True
1162 try:
1163 while True:
1164 if _WIN:
1165 outbuf = lltype.malloc(rffi.CWCHARP.TO, i, flavor='raw')
1166 else:
1167 outbuf = lltype.malloc(rffi.CCHARP.TO, i, flavor='raw')
1168 try:
1169 with rposix.SuppressIPH():
1170 buflen = c_strftime(outbuf, i, format_for_call, buf_value)
1171 if _WIN and buflen == 0 and rposix.get_saved_errno() == errno.EINVAL:
1172 raise oefmt(space.w_ValueError, "invalid format string")
1173 if buflen > 0 or i >= 256 * len(format):
1174 # if the buffer is 256 times as long as the format,
1175 # it's probably not failing for lack of room!
1176 # More likely, the format yields an empty result,
1177 # e.g. an empty format, or %Z when the timezone
1178 # is unknown.
1179 if _WIN:
1180 decoded, size = rffi.wcharp2utf8n(outbuf, intmask(buflen))
1181 else:
1182 result = rffi.charp2strn(outbuf, intmask(buflen))
1183 if passthrough:
1184 decoded = result
1185 size = codepoints_in_utf8(result)
1186 else:
1187 decoded, size = str_decode_locale_surrogateescape(result)
1188 return space.newutf8(decoded, size)
1189 finally:
1190 lltype.free(outbuf, flavor='raw')
1191 i += i
1192 finally:
1193 if _WIN:
1194 rffi.free_wcharp(format_for_call)
1195
1196 def _monotonic_impl(space, w_info):
1197 with lltype.scoped_alloc(rffi.CArray(pytime_t), 1) as t:
1198 if w_info:
1199 with lltype.scoped_alloc(rffi.CArray(clock_info_t), 1) as info:
1200 res = _PyTime_GetMonotonicClockWithInfo(t, info)
1201 implementation = rffi.constcharp2str(info[0].c_implementation)
1202 resolution = info[0].c_resolution
1203 mono = bool(widen(info[0].c_monotonic))
1204 adjust = bool(widen(info[0].c_adjustable))
1205 _setinfo(space, w_info, implementation, resolution, mono, adjust)
1206
1207 else:
1208 res = _PyTime_GetMonotonicClockWithInfo(t, rffi.cast(rffi.CArrayPtr(clock_info_t), 0))
1209 if res < 0:
1210 raise oefmt(space.w_RuntimeError, "could not get montonic clock")
1211 return t[0]
1212
1213
1214 def _monotonic(space):
1215 t = _monotonic_impl(space, None)
1216 d = _PyTime_AsSecondsDouble(t)
1217 return d
1218
1219 def monotonic(space):
1220 """monotonic() -> float
1221
1222 Monotonic clock, cannot go backward."""
1223 d = _monotonic(space)
1224 return space.newfloat(d)
1225
1226 def monotonic_ns(space):
1227 """monotonic_ns() -> int
1228
1229 Monotonic clock, cannot go backward, as nanoseconds."""
1230 t = _monotonic_impl(space, None)
1231 return space.newint(t)
1232
1233 def _perf_counter_impl(space, w_info):
1234 with lltype.scoped_alloc(rffi.CArray(pytime_t), 1) as t:
1235 if w_info:
1236 with lltype.scoped_alloc(rffi.CArray(clock_info_t), 1) as info:
1237 res = _PyTime_GetPerfCounterWithInfo(t, info)
1238 implementation = rffi.constcharp2str(info[0].c_implementation)
1239 resolution = info[0].c_resolution
1240 mono = bool(widen(info[0].c_monotonic))
1241 adjust = bool(widen(info[0].c_adjustable))
1242 _setinfo(space, w_info, implementation, resolution, mono, adjust)
1243
1244 else:
1245 res = _PyTime_GetPerfCounterWithInfo(t, rffi.cast(rffi.CArrayPtr(clock_info_t), 0))
1246 if res < 0:
1247 raise oefmt(space.w_RuntimeError, "could not get perf_counter")
1248 return t[0]
1249
1250 def perf_counter(space):
1251 """perf_counter() -> float
1252
1253 Performance counter for benchmarking."""
1254
1255 t = _perf_counter_impl(space, None)
1256 d = _PyTime_AsSecondsDouble(t)
1257 return space.newfloat(d)
1258
1259 def perf_counter_ns(space):
1260 """perf_counter_ns() -> int
1261
1262 Performance counter for benchmarking as nanoseconds."""
1263 t = _perf_counter_impl(space, None)
1264 return space.newint(t)
1265
1266
1267 if _WIN:
1268 def _process_time_impl(space, w_info, return_ns):
1269 from rpython.rlib.rposix import GetCurrentProcess, GetProcessTimes
1270 current_process = GetCurrentProcess()
1271 with lltype.scoped_alloc(rwin32.FILETIME) as creation_time, \
1272 lltype.scoped_alloc(rwin32.FILETIME) as exit_time, \
1273 lltype.scoped_alloc(rwin32.FILETIME) as kernel_time, \
1274 lltype.scoped_alloc(rwin32.FILETIME) as user_time:
1275 worked = GetProcessTimes(current_process, creation_time, exit_time,
1276 kernel_time, user_time)
1277 if not worked:
1278 raise wrap_oserror(space,
1279 rwin32.lastSavedWindowsError("GetProcessTimes"))
1280 kernel_time2 = (kernel_time.c_dwLowDateTime |
1281 r_ulonglong(kernel_time.c_dwHighDateTime) << 32)
1282 user_time2 = (user_time.c_dwLowDateTime |
1283 r_ulonglong(user_time.c_dwHighDateTime) << 32)
1284 if w_info is not None:
1285 _setinfo(space, w_info, "GetProcessTimes()", 1e-7, True, False)
1286 if return_ns:
1287 return space.newint((tolong(kernel_time2) +
1288 tolong(user_time2)) * 100)
1289 else:
1290 return space.newfloat((float(kernel_time2) +
1291 float(user_time2)) * 1e-7)
1292 else:
1293 have_times = hasattr(rposix, 'c_times')
1294
1295 def _process_time_impl(space, w_info, return_ns):
1296 if HAS_CLOCK_GETTIME_RUNTIME and (
1297 rtime.CLOCK_PROF is not None or
1298 rtime.CLOCK_PROCESS_CPUTIME_ID is not None):
1299 if rtime.CLOCK_PROF is not None:
1300 clk_id = rtime.CLOCK_PROF
1301 implementation = "clock_gettime(CLOCK_PROF)"
1302 else:
1303 clk_id = rtime.CLOCK_PROCESS_CPUTIME_ID
1304 implementation = "clock_gettime(CLOCK_PROCESS_CPUTIME_ID)"
1305 with lltype.scoped_alloc(TIMESPEC) as timespec:
1306 ret = c_clock_gettime(clk_id, timespec)
1307 if ret == 0:
1308 if w_info is not None:
1309 with lltype.scoped_alloc(TIMESPEC) as tsres:
1310 ret = c_clock_getres(clk_id, tsres)
1311 if ret == 0:
1312 res = _timespec_to_seconds(tsres)
1313 else:
1314 res = 1e-9
1315 _setinfo(space, w_info,
1316 implementation, res, True, False)
1317 if return_ns:
1318 return space.newint(_timespec_to_nanoseconds(timespec))
1319 else:
1320 return space.newfloat(_timespec_to_seconds(timespec))
1321
1322 if True: # XXX available except if it isn't?
1323 from rpython.rlib.rtime import (c_getrusage, RUSAGE, RUSAGE_SELF,
1324 decode_timeval, decode_timeval_ns)
1325 with lltype.scoped_alloc(RUSAGE) as rusage:
1326 ret = c_getrusage(RUSAGE_SELF, rusage)
1327 if ret == 0:
1328 if w_info is not None:
1329 _setinfo(space, w_info,
1330 "getrusage(RUSAGE_SELF)", 1e-6, True, False)
1331 if return_ns:
1332 return space.newint(
1333 decode_timeval_ns(rusage.c_ru_utime) +
1334 decode_timeval_ns(rusage.c_ru_stime))
1335 else:
1336 return space.newfloat(decode_timeval(rusage.c_ru_utime) +
1337 decode_timeval(rusage.c_ru_stime))
1338 if have_times:
1339 with lltype.scoped_alloc(rposix.TMS) as tms:
1340 ret = rposix.c_times(tms)
1341 if rffi.cast(lltype.Signed, ret) != -1:
1342 cpu_time = (rffi.cast(lltype.Signed, tms.c_tms_utime) +
1343 rffi.cast(lltype.Signed, tms.c_tms_stime))
1344 if w_info is not None:
1345 _setinfo(space, w_info, "times()",
1346 1.0 / rposix.CLOCK_TICKS_PER_SECOND,
1347 True, False)
1348 if return_ns:
1349 return space.newint(r_int64(cpu_time) * 10**9 // int(rposix.CLOCK_TICKS_PER_SECOND))
1350 else:
1351 return space.newfloat(float(cpu_time) / rposix.CLOCK_TICKS_PER_SECOND)
1352 return _clock_impl(space, w_info, return_ns)
1353
1354 def process_time(space):
1355 """process_time() -> float
1356
1357 Process time for profiling: sum of the kernel and user-space CPU time."""
1358 return _process_time_impl(space, None, False)
1359
1360 def process_time_ns(space):
1361 """process_time() -> int
1362
1363 Process time for profiling as nanoseconds:
1364 sum of the kernel and user-space CPU time"""
1365 return _process_time_impl(space, None, True)
1366
1367 if HAS_THREAD_TIME:
1368 if _WIN:
1369 FILETIME_P = lltype.Ptr(rwin32.FILETIME)
1370 _GetCurrentThread = rwin32.winexternal('GetCurrentThread', [], rwin32.HANDLE)
1371 _GetThreadTimes = rwin32.winexternal('GetThreadTimes',
1372 [rwin32.HANDLE, FILETIME_P, FILETIME_P, FILETIME_P, FILETIME_P],
1373 rwin32.BOOL)
1374 def _thread_time_impl(space, w_info, return_ns):
1375 thread = _GetCurrentThread()
1376
1377 with lltype.scoped_alloc(rwin32.FILETIME) as creation_time, \
1378 lltype.scoped_alloc(rwin32.FILETIME) as exit_time, \
1379 lltype.scoped_alloc(rwin32.FILETIME) as kernel_time, \
1380 lltype.scoped_alloc(rwin32.FILETIME) as user_time:
1381 ok = _GetThreadTimes(thread, creation_time, exit_time,
1382 kernel_time, user_time)
1383 if not ok:
1384 raise wrap_oserror(space,
1385 rwin32.lastSavedWindowsError("GetThreadTimes"))
1386 ktime = (kernel_time.c_dwLowDateTime |
1387 r_ulonglong(kernel_time.c_dwHighDateTime) << 32)
1388 utime = (user_time.c_dwLowDateTime |
1389 r_ulonglong(user_time.c_dwHighDateTime) << 32)
1390
1391 if w_info is not None:
1392 _setinfo(space, w_info, "GetThreadTimes()", 1e-7, True, False)
1393
1394 # ktime and utime have a resolution of 100 nanoseconds
1395 if return_ns:
1396 return space.newint((tolong(ktime) + tolong(utime)) * 10**2)
1397 else:
1398 return space.newfloat((float(ktime) + float(utime)) * 1e-7)
1399 else:
1400 def _thread_time_impl(space, w_info, return_ns):
1401 clk_id = rtime.CLOCK_THREAD_CPUTIME_ID
1402 implementation = "clock_gettime(CLOCK_THREAD_CPUTIME_ID)"
1403
1404 with lltype.scoped_alloc(TIMESPEC) as timespec:
1405 ret = c_clock_gettime(clk_id, timespec)
1406 if ret == 0:
1407 if w_info is not None:
1408 with lltype.scoped_alloc(TIMESPEC) as tsres:
1409 ret = c_clock_getres(clk_id, tsres)
1410 if ret == 0:
1411 res = _timespec_to_seconds(tsres)
1412 else:
1413 res = 1e-9
1414 _setinfo(space, w_info, implementation, res, True, False)
1415 if return_ns:
1416 return space.newint(_timespec_to_nanoseconds(timespec))
1417 else:
1418 return space.newfloat(_timespec_to_seconds(timespec))
1419
1420 def thread_time(space):
1421 """thread_time() -> float
1422
1423 Thread time for profiling: sum of the kernel and user-space CPU time."""
1424 return _thread_time_impl(space, None, False)
1425
1426 def thread_time_ns(space):
1427 """thread_time_ns() -> int
1428
1429 Thread time for profiling as nanoseconds:
1430 sum of the kernel and user-space CPU time."""
1431 return _thread_time_impl(space, None, True)
1432
1433
1434 _clock = external('clock', [], rposix.CLOCK_T)
1435 def _clock_impl(space, w_info, return_ns):
1436 if _WIN:
1437 try:
1438 return _win_perf_counter_impl(space, w_info, return_ns)
1439 except ValueError:
1440 pass
1441 value = widen(_clock())
1442 if value == widen(rffi.cast(rposix.CLOCK_T, -1)):
1443 raise oefmt(space.w_RuntimeError,
1444 "the processor time used is not available or its value"
1445 "cannot be represented")
1446
1447 if _MACOSX:
1448 # small hack apparently solving unsigned int on mac
1449 value = intmask(value)
1450
1451 if w_info is not None:
1452 _setinfo(space, w_info, "clock()", 1.0 / CLOCKS_PER_SEC, True, False)
1453 if return_ns:
1454 return space.newint(r_int64(value) * 10**9 // CLOCKS_PER_SEC)
1455 else:
1456 return space.newfloat(float(value) / CLOCKS_PER_SEC)
1457
1458
1459 def _setinfo(space, w_info, impl, res, mono, adj):
1460 space.setattr(w_info, space.newtext('implementation'), space.newtext(impl))
1461 space.setattr(w_info, space.newtext('resolution'), space.newfloat(res))
1462 space.setattr(w_info, space.newtext('monotonic'), space.newbool(mono))
1463 space.setattr(w_info, space.newtext('adjustable'), space.newbool(adj))