Skip to content

Instantly share code, notes, and snippets.

@eisensheng
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eisensheng/d3a34dfe095b92d035f9 to your computer and use it in GitHub Desktop.
Save eisensheng/d3a34dfe095b92d035f9 to your computer and use it in GitHub Desktop.
python, time and sleep
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
from select import select
from cffi import FFI
ffi = FFI()
ffi.cdef("""
#define CLOCK_REALTIME ...
#define CLOCK_MONOTONIC ...
#define CLOCK_PROCESS_CPUTIME_ID ...
#define CLOCK_THREAD_CPUTIME_ID ...
#define CLOCK_MONOTONIC_RAW ...
#define CLOCK_REALTIME_COARSE ...
#define CLOCK_MONOTONIC_COARSE ...
#define CLOCK_BOOTTIME ...
typedef int clockid_t;
struct timespec
{
long tv_sec; /* Seconds. */
long tv_nsec; /* Nanoseconds. */
};
int clock_getres (clockid_t __clock_id, struct timespec *__res);
int clock_gettime (clockid_t __clock_id, struct timespec *__tp);
int clock_settime (clockid_t __clock_id, const struct timespec *__tp);
int nanosleep (const struct timespec *__requested_time,
struct timespec *__remaining);
""")
ffi_lib = ffi.verify("""
#include <time.h>
""", libraries=['rt', ])
def _ts_to_float(ts):
return ts.tv_sec + ts.tv_nsec / 1e9
def nano_sleep(value):
ts_a = ffi.new('struct timespec *')
ts_a.tv_sec, ts_a.tv_nsec = int(value), int((value - int(value)) * 1e9)
ts_b = ffi.new('struct timespec *')
ffi_lib.nanosleep(ts_a, ts_b)
return _ts_to_float(ts_b)
def clock_get_resolution(clock_id):
ts = ffi.new('struct timespec *')
if ffi_lib.clock_getres(clock_id, ts) < 0:
raise OSError(ffi.errno, 'clock_getres failed')
return _ts_to_float(ts)
def clock_get_time(clock_id):
ts = ffi.new('struct timespec *')
if ffi_lib.clock_gettime(clock_id, ts) < 0:
raise OSError(ffi.errno, 'clock_gettime failed')
return _ts_to_float(ts)
def monotonic():
return clock_get_time(ffi_lib.CLOCK_MONOTONIC)
while True:
a = monotonic()
nano_sleep(3.)
b = monotonic()
print('nsleep:', b - a)
a = monotonic()
select([], [], [], 3.)
b = monotonic()
print('select:', b - a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment