Skip to content

Instantly share code, notes, and snippets.

@olavmrk
Last active August 29, 2015 14:10
Show Gist options
  • Save olavmrk/e1aa8c0b05e3b8e8f5a5 to your computer and use it in GitHub Desktop.
Save olavmrk/e1aa8c0b05e3b8e8f5a5 to your computer and use it in GitHub Desktop.
Clock debugging script.
#!/usr/bin/env python
import ctypes
import ntplib # wget https://ntplib.googlecode.com/hg/ntplib.py
import sys
import time
# struct timespec {
# time_t tv_sec; /* seconds */
# long tv_nsec; /* nanoseconds */
# };
class TimeSpec(ctypes.Structure):
_fields_ = [
('tv_sec', ctypes.c_long),
('tv_nsec', ctypes.c_long),
]
librt = ctypes.CDLL('librt.so.1', use_errno=True)
clock_gettime_raw = librt.clock_gettime
clock_gettime_raw.argtypes = [ ctypes.c_int, ctypes.POINTER(TimeSpec) ]
clock_gettime_raw.restype = ctypes.c_int
def clock_gettime(clock):
ts = TimeSpec()
res = clock_gettime_raw(clock, ctypes.pointer(ts))
if res < 0:
raise Exception('Error calling clock_gettime({clock}): {errno}'.format(clock=clock, errno=ctypes.get_errno()))
return ts.tv_sec + ts.tv_nsec / 1000000000.0
CLOCK_REALTIME = 0
CLOCK_MONOTONIC = 1
CLOCK_MONOTONIC_RAW = 4
CLOCK_BOOTTIME = 7
def ntp_timegetter(server):
nc = ntplib.NTPClient()
try:
res = nc.request(server, timeout=1)
offset = res.offset
except:
offset = None
def get():
if offset is None:
return None
return offset + time.time()
return get
def fmt_ts(ts):
if ts is None:
return '- '
secs = int(ts)
nsecs = int((ts - secs) * 1000000000)
return time.strftime('%Y-%m-%dT%H:%M:%S', time.gmtime(secs)) + '.%09dZ' % nsecs
def fmt_mt(ts):
return '%020.9f' % (ts)
print 'FL OFFSET REALTIME MONOTONIC MONOTONIC_RAW NTP1 NTP2 '
while True:
ntp1 = ntp_timegetter('0.pool.ntp.org')
ntp2 = ntp_timegetter('1.pool.ntp.org')
realtime = clock_gettime(CLOCK_REALTIME)
monotonic = clock_gettime(CLOCK_MONOTONIC)
monotonic_raw = clock_gettime(CLOCK_MONOTONIC_RAW)
ntp1 = ntp1()
ntp2 = ntp2()
if ntp1 is not None and ntp2 is not None:
offset = (ntp1 + ntp2) / 2.0 - realtime
elif ntp1 is not None:
offset = ntp1 - realtime
elif ntp2 is not None:
offset = ntp2 - realtime
else:
offset = None
flag = '!' if offset is not None and abs(offset) > 0.5 else ' '
offset = '% 7.3f' % offset
print flag, offset, fmt_ts(realtime), fmt_mt(monotonic), fmt_mt(monotonic_raw), fmt_ts(ntp1), fmt_ts(ntp2)
sys.stdout.flush()
time.sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment