Mercurial > hg > python-clock
comparison clock.pyx @ 0:1c0396a8fff4 default tip
Import
author | Daniele Nicolodi <daniele.nicolodi@obspm.fr> |
---|---|
date | Fri, 03 Jul 2015 21:00:16 +0200 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:1c0396a8fff4 |
---|---|
1 from libc.errno cimport * | |
2 from libc.stdio cimport snprintf | |
3 | |
4 cdef extern from "time.h": | |
5 ctypedef long time_t | |
6 cdef struct _timespec "timespec": | |
7 time_t tv_sec | |
8 long tv_nsec | |
9 cdef enum: | |
10 CLOCK_MONOTONIC | |
11 CLOCK_REALTIME | |
12 cdef enum: | |
13 TIMER_ABSTIME | |
14 int clock_gettime(int id, _timespec *tp) nogil | |
15 int clock_nanosleep(int id, int flags, | |
16 _timespec *request, | |
17 _timespec *remain) nogil | |
18 | |
19 | |
20 cdef class timespec: | |
21 cdef _timespec t | |
22 | |
23 def __init__(self, long sec=0, long nsec=0): | |
24 self.t.tv_sec = sec | |
25 self.t.tv_nsec = nsec | |
26 | |
27 property sec: | |
28 def __get__(self): | |
29 return self.t.tv_sec | |
30 def __set__(self, long v): | |
31 self.t.tv_sec = v | |
32 | |
33 property nsec: | |
34 def __get__(self): | |
35 return self.t.tv_nsec | |
36 def __set__(self, long v): | |
37 self.t.tv_nsec = v | |
38 while self.t.tv_nsec >= 1000000000: | |
39 self.t.tv_sec += 1 | |
40 self.t.tv_nsec -= 1000000000 | |
41 | |
42 def __add__(self, long v): | |
43 self.sec += v | |
44 return self | |
45 | |
46 def __float__(self): | |
47 return self.t.tv_sec + self.t.tv_nsec * 1e-9 | |
48 | |
49 def __repr__(self): | |
50 cdef char[64] s | |
51 snprintf(s, 64, "{ sec=%ld nsec=%ld }", self.t.tv_sec, self.t.tv_nsec) | |
52 return s | |
53 | |
54 | |
55 def gettime(clockid=CLOCK_REALTIME): | |
56 t = timespec() | |
57 clock_gettime(clockid, &t.t) | |
58 return t | |
59 | |
60 | |
61 def nanosleep(timespec request, int clockid=CLOCK_REALTIME, bint absolute=False): | |
62 cdef _timespec remain | |
63 cdef int flags = 0 | |
64 cdef int r | |
65 cdef _timespec *t = &request.t | |
66 | |
67 if absolute: | |
68 flags = flags | TIMER_ABSTIME | |
69 | |
70 with nogil: | |
71 while 1: | |
72 r = clock_nanosleep(clockid, flags, t, &remain) | |
73 if r == EINTR: | |
74 if not absolute: | |
75 t = &remain | |
76 continue | |
77 break | |
78 | |
79 if r != 0: | |
80 raise ValueError |