| 1 |
import time |
| 2 |
import unittest |
| 3 |
from test.support import import_helper |
| 4 |
_testcapi = import_helper.import_module('_testcapi') |
| 5 |
|
| 6 |
|
| 7 |
PyTime_MIN = _testcapi.PyTime_MIN |
| 8 |
PyTime_MAX = _testcapi.PyTime_MAX |
| 9 |
SEC_TO_NS = 10 ** 9 |
| 10 |
DAY_TO_SEC = (24 * 60 * 60) |
| 11 |
# Worst clock resolution: maximum delta between two clock reads. |
| 12 |
CLOCK_RES = 0.050 |
| 13 |
|
| 14 |
|
| 15 |
class CAPITest(unittest.TestCase): |
| 16 |
def test_min_max(self): |
| 17 |
# PyTime_t is just int64_t |
| 18 |
self.assertEqual(PyTime_MIN, -2**63) |
| 19 |
self.assertEqual(PyTime_MAX, 2**63 - 1) |
| 20 |
|
| 21 |
def test_assecondsdouble(self): |
| 22 |
# Test PyTime_AsSecondsDouble() |
| 23 |
def ns_to_sec(ns): |
| 24 |
if abs(ns) % SEC_TO_NS == 0: |
| 25 |
return float(ns // SEC_TO_NS) |
| 26 |
else: |
| 27 |
return float(ns) / SEC_TO_NS |
| 28 |
|
| 29 |
seconds = ( |
| 30 |
0, |
| 31 |
1, |
| 32 |
DAY_TO_SEC, |
| 33 |
365 * DAY_TO_SEC, |
| 34 |
) |
| 35 |
values = { |
| 36 |
PyTime_MIN, |
| 37 |
PyTime_MIN + 1, |
| 38 |
PyTime_MAX - 1, |
| 39 |
PyTime_MAX, |
| 40 |
} |
| 41 |
for second in seconds: |
| 42 |
ns = second * SEC_TO_NS |
| 43 |
values.add(ns) |
| 44 |
# test nanosecond before/after to test rounding |
| 45 |
values.add(ns - 1) |
| 46 |
values.add(ns + 1) |
| 47 |
for ns in list(values): |
| 48 |
if (-ns) > PyTime_MAX: |
| 49 |
continue |
| 50 |
values.add(-ns) |
| 51 |
for ns in sorted(values): |
| 52 |
with self.subTest(ns=ns): |
| 53 |
self.assertEqual(_testcapi.PyTime_AsSecondsDouble(ns), |
| 54 |
ns_to_sec(ns)) |
| 55 |
|
| 56 |
def check_clock(self, c_func, py_func): |
| 57 |
t1 = c_func() |
| 58 |
t2 = py_func() |
| 59 |
self.assertAlmostEqual(t1, t2, delta=CLOCK_RES) |
| 60 |
|
| 61 |
def test_monotonic(self): |
| 62 |
# Test PyTime_Monotonic() and PyTime_MonotonicRaw() |
| 63 |
self.check_clock(_testcapi.PyTime_Monotonic, time.monotonic) |
| 64 |
self.check_clock(_testcapi.PyTime_MonotonicRaw, time.monotonic) |
| 65 |
|
| 66 |
def test_perf_counter(self): |
| 67 |
# Test PyTime_PerfCounter() and PyTime_PerfCounterRaw() |
| 68 |
self.check_clock(_testcapi.PyTime_PerfCounter, time.perf_counter) |
| 69 |
self.check_clock(_testcapi.PyTime_PerfCounterRaw, time.perf_counter) |
| 70 |
|
| 71 |
def test_time(self): |
| 72 |
# Test PyTime_Time() and PyTime_TimeRaw() |
| 73 |
self.check_clock(_testcapi.PyTime_Time, time.time) |
| 74 |
self.check_clock(_testcapi.PyTime_TimeRaw, time.time) |
| 75 |
|
| 76 |
|
| 77 |
if __name__ == "__main__": |
| 78 |
unittest.main() |