Debian Codegraph @

rpython/rlib/rtime.py

raw symbols SCIP
1 """
2 RPython implementations of time.time(), time.clock(), time.select().
3 """
4
5 import sys
6 import math
7 import time as pytime
8 from rpython.translator.tool.cbuild import ExternalCompilationInfo
9 from rpython.rtyper.tool import rffi_platform
10 from rpython.rtyper.lltypesystem import rffi, lltype
11 from rpython.rlib.objectmodel import register_replacement_for
12 from rpython.rlib.rarithmetic import intmask, r_int64, UINT_MAX
13 from rpython.rlib import rposix
14
15 _WIN32 = sys.platform.startswith('win')
16
17 if _WIN32:
18 TIME_H = 'time.h'
19 FTIME = '_ftime64'
20 STRUCT_TIMEB = 'struct __timeb64'
21 includes = ['winsock2.h', 'windows.h',
22 TIME_H, 'sys/types.h', 'sys/timeb.h']
23 need_rusage = False
24 else:
25 TIME_H = 'sys/time.h'
26 FTIME = 'ftime'
27 STRUCT_TIMEB = 'struct timeb'
28 includes = [TIME_H, 'time.h', 'errno.h', 'sys/select.h',
29 'sys/types.h', 'unistd.h',
30 'sys/time.h', 'sys/resource.h']
31
32 if not sys.platform.startswith("openbsd") and \
33 not sys.platform.startswith("freebsd"):
34 includes.append('sys/timeb.h')
35
36 need_rusage = True
37
38
39 eci = ExternalCompilationInfo(includes=includes)
40
41 class CConfig:
42 _compilation_info_ = eci
43 TIMEVAL = rffi_platform.Struct('struct timeval', [('tv_sec', rffi.INT),
44 ('tv_usec', rffi.INT)])
45 if not _WIN32:
46 TIMEZONE = rffi_platform.Struct('struct timezone', [
47 ('tz_minuteswest', rffi.INT_real),
48 ('tz_dsttime', rffi.INT_real),
49 ])
50 HAVE_GETTIMEOFDAY = rffi_platform.Has('gettimeofday')
51 HAVE_FTIME = rffi_platform.Has(FTIME)
52 HAVE_NANOSLEEP = rffi_platform.Has('nanosleep')
53 HAVE_CLOCK_NANOSLEEP = rffi_platform.Has('clock_nanosleep')
54 if need_rusage:
55 RUSAGE = rffi_platform.Struct('struct rusage', [('ru_utime', TIMEVAL),
56 ('ru_stime', TIMEVAL)])
57
58 if sys.platform.startswith('freebsd') or sys.platform.startswith('netbsd'):
59 libraries = ['compat']
60 elif sys.platform == 'linux2':
61 libraries = ['rt']
62 else:
63 libraries = []
64
65 class CConfigForFTime:
66 _compilation_info_ = ExternalCompilationInfo(
67 includes=[TIME_H, 'sys/timeb.h'],
68 libraries=libraries
69 )
70 TIMEB = rffi_platform.Struct(STRUCT_TIMEB, [('time', rffi.INT),
71 ('millitm', rffi.INT)])
72
73 class CConfigForClockGetTime:
74 _compilation_info_ = ExternalCompilationInfo(
75 includes=['time.h'],
76 libraries=libraries
77 )
78 _NO_MISSING_RT = rffi_platform.Has('printf("%d", clock_gettime(0, 0))')
79 TIMESPEC = rffi_platform.Struct('struct timespec', [('tv_sec', rffi.LONG),
80 ('tv_nsec', rffi.LONG)])
81
82 constant_names = ['RUSAGE_SELF', 'EINTR',
83 'CLOCK_REALTIME',
84 'CLOCK_REALTIME_COARSE',
85 'CLOCK_MONOTONIC',
86 'CLOCK_MONOTONIC_COARSE',
87 'CLOCK_MONOTONIC_RAW',
88 'CLOCK_BOOTTIME',
89 'CLOCK_PROCESS_CPUTIME_ID',
90 'CLOCK_THREAD_CPUTIME_ID',
91 'CLOCK_HIGHRES',
92 'CLOCK_PROF',
93 'CLOCK_UPTIME',
94 ]
95 for const in constant_names:
96 setattr(CConfig, const, rffi_platform.DefinedConstantInteger(const))
97 defs_names = ['GETTIMEOFDAY_NO_TZ']
98 for const in defs_names:
99 setattr(CConfig, const, rffi_platform.Defined(const))
100
101 def decode_timeval(t):
102 return (float(rffi.getintfield(t, 'c_tv_sec')) +
103 float(rffi.getintfield(t, 'c_tv_usec')) * 0.000001)
104
105 def decode_timeval_ns(t):
106 return (r_int64(rffi.getintfield(t, 'c_tv_sec')) * 10**9 +
107 r_int64(rffi.getintfield(t, 'c_tv_usec')) * 10**3)
108
109
110 def external(name, args, result, compilation_info=eci, **kwds):
111 return rffi.llexternal(name, args, result,
112 compilation_info=compilation_info, **kwds)
113
114 def replace_time_function(name):
115 func = getattr(pytime, name, None)
116 if func is None:
117 return lambda f: f
118 return register_replacement_for(
119 func,
120 sandboxed_name='ll_time.ll_time_%s' % name)
121
122 config = rffi_platform.configure(CConfig)
123 globals().update(config)
124
125 # Note: time.time() is used by the framework GC during collect(),
126 # which means that we have to be very careful about not allocating
127 # GC memory here. This is the reason for the _nowrapper=True.
128 if HAVE_GETTIMEOFDAY:
129 if GETTIMEOFDAY_NO_TZ:
130 c_gettimeofday = external('gettimeofday',
131 [lltype.Ptr(TIMEVAL)], rffi.INT,
132 _nowrapper=True, releasegil=False)
133 else:
134 c_gettimeofday = external('gettimeofday',
135 [lltype.Ptr(TIMEVAL), lltype.Ptr(TIMEZONE)], rffi.INT,
136 _nowrapper=True, releasegil=False)
137 if HAVE_FTIME:
138 globals().update(rffi_platform.configure(CConfigForFTime))
139 c_ftime = external(FTIME, [lltype.Ptr(TIMEB)],
140 lltype.Void,
141 _nowrapper=True, releasegil=False)
142 c_time = external('time', [rffi.VOIDP], rffi.TIME_T,
143 _nowrapper=True, releasegil=False)
144
145
146 @replace_time_function('time')
147 def time():
148 void = lltype.nullptr(rffi.VOIDP.TO)
149 result = -1.0
150 if HAVE_GETTIMEOFDAY:
151 # NB: can't use lltype.scoped_malloc, because that will allocate the
152 # with handler in the GC, but we want to use time.time from gc.collect!
153 t = lltype.malloc(TIMEVAL, flavor='raw')
154 try:
155 errcode = -1
156 if GETTIMEOFDAY_NO_TZ:
157 errcode = c_gettimeofday(t)
158 else:
159 tzvoid = rffi.cast(lltype.Ptr(TIMEZONE), 0)
160 errcode = c_gettimeofday(t, tzvoid)
161
162 if rffi.cast(rffi.LONG, errcode) == 0:
163 result = decode_timeval(t)
164 finally:
165 lltype.free(t, flavor='raw')
166 if result != -1:
167 return result
168 else: # assume using ftime(3)
169 t = lltype.malloc(TIMEB, flavor='raw')
170 try:
171 c_ftime(t)
172 result = (float(intmask(t.c_time)) +
173 float(intmask(t.c_millitm)) * 0.001)
174 finally:
175 lltype.free(t, flavor='raw')
176 return result
177 return float(c_time(void))
178
179
180 # _______________________________________________________________
181 # time.clock()
182
183 if _WIN32:
184 # hacking to avoid LARGE_INTEGER which is a union...
185 QueryPerformanceCounter = external(
186 'QueryPerformanceCounter', [rffi.CArrayPtr(lltype.SignedLongLong)],
187 lltype.Void, releasegil=False)
188 QueryPerformanceFrequency = external(
189 'QueryPerformanceFrequency', [rffi.CArrayPtr(lltype.SignedLongLong)],
190 rffi.INT, releasegil=False)
191 class State(object):
192 divisor = 0.0
193 counter_start = 0
194 state = State()
195
196 HAS_CLOCK_GETTIME_RUNTIME = (CLOCK_MONOTONIC is not None)
197 if sys.platform == 'darwin':
198 HAS_CLOCK_GETTIME_RUNTIME = True
199 # ^^^ issue #2432 and others
200 # (change it manually if you *know* you want to build and run on
201 # OS/X 10.12 or later)
202 # 2024-11-11: changed to True since translator.platform.darwin uses
203 # macos-version-min=10.13
204
205 if HAS_CLOCK_GETTIME_RUNTIME:
206 # Linux and other POSIX systems with clock_gettime()
207 # TIMESPEC:
208 globals().update(rffi_platform.configure(CConfigForClockGetTime))
209 # do we need to add -lrt?
210 eciclock = CConfigForClockGetTime._compilation_info_
211 if not _NO_MISSING_RT:
212 eciclock = eciclock.merge(ExternalCompilationInfo(libraries=['rt']))
213 # the functions:
214 c_clock_getres = external("clock_getres",
215 [lltype.Signed, lltype.Ptr(TIMESPEC)],
216 rffi.INT, releasegil=False,
217 save_err=rffi.RFFI_SAVE_ERRNO,
218 compilation_info=eciclock)
219 c_clock_gettime = external('clock_gettime',
220 [lltype.Signed, lltype.Ptr(TIMESPEC)],
221 rffi.INT, releasegil=False,
222 save_err=rffi.RFFI_SAVE_ERRNO,
223 compilation_info=eciclock)
224 c_clock_settime = external('clock_settime',
225 [lltype.Signed, lltype.Ptr(TIMESPEC)],
226 rffi.INT, releasegil=False,
227 save_err=rffi.RFFI_SAVE_ERRNO,
228 compilation_info=eciclock)
229 # Note: there is no higher-level functions here to access
230 # clock_gettime(). The issue is that we'd need a way that keeps
231 # nanosecond precision, depending on the usage, so we can't have a
232 # nice function that returns the time as a float.
233 ALL_DEFINED_CLOCKS = [const for const in constant_names
234 if const.startswith('CLOCK_')
235 and globals()[const] is not None]
236
237 if need_rusage:
238 RUSAGE = RUSAGE
239 RUSAGE_SELF = RUSAGE_SELF or 0
240 c_getrusage = external('getrusage',
241 [rffi.INT, lltype.Ptr(RUSAGE)],
242 rffi.INT,
243 releasegil=False)
244
245 def win_perf_counter():
246 with lltype.scoped_alloc(rffi.CArray(rffi.lltype.SignedLongLong), 1) as a:
247 if state.divisor == 0.0:
248 QueryPerformanceCounter(a)
249 state.counter_start = a[0]
250 QueryPerformanceFrequency(a)
251 state.divisor = float(a[0])
252 QueryPerformanceCounter(a)
253 diff = a[0] - state.counter_start
254 return float(diff) / state.divisor
255
256 @replace_time_function('clock')
257 def clock():
258 if _WIN32:
259 return win_perf_counter()
260 elif HAS_CLOCK_GETTIME_RUNTIME and CLOCK_PROCESS_CPUTIME_ID is not None:
261 with lltype.scoped_alloc(TIMESPEC) as a:
262 if c_clock_gettime(CLOCK_PROCESS_CPUTIME_ID, a) == 0:
263 return (float(rffi.getintfield(a, 'c_tv_sec')) +
264 float(rffi.getintfield(a, 'c_tv_nsec')) * 0.000000001)
265 with lltype.scoped_alloc(RUSAGE) as a:
266 c_getrusage(RUSAGE_SELF, a)
267 result = (decode_timeval(a.c_ru_utime) +
268 decode_timeval(a.c_ru_stime))
269 return result
270
271 # _______________________________________________________________
272 # time.sleep()
273
274 if _WIN32:
275 Sleep = external('Sleep', [rffi.ULONG], lltype.Void, releasegil=True)
276 else:
277 c_select = external('select', [rffi.INT, rffi.VOIDP,
278 rffi.VOIDP, rffi.VOIDP,
279 lltype.Ptr(TIMEVAL)], rffi.INT,
280 save_err=rffi.RFFI_SAVE_ERRNO)
281
282 @replace_time_function('sleep')
283 def sleep(secs):
284 if _WIN32:
285 millisecs = secs * 1000.0
286 while millisecs > UINT_MAX:
287 Sleep(UINT_MAX)
288 millisecs -= UINT_MAX
289 Sleep(rffi.cast(rffi.ULONG, int(millisecs)))
290 else:
291 void = lltype.nullptr(rffi.VOIDP.TO)
292 with lltype.scoped_alloc(TIMEVAL) as t:
293 frac = int(math.fmod(secs, 1.0) * 1000000.)
294 assert frac >= 0
295 rffi.setintfield(t, 'c_tv_sec', int(secs))
296 rffi.setintfield(t, 'c_tv_usec', frac)
297
298 if rffi.cast(rffi.LONG, c_select(0, void, void, void, t)) != 0:
299 errno = rposix.get_saved_errno()
300 if errno != EINTR:
301 raise OSError(errno, "Select failed")