Skip to content

Commit 8a71757

Browse files
committed
Use time.monotonic()
time.monotonic() relates to the real time spent inside the main thread, and can not be altered externally by e.g. - ntp system time synchronisation (frequent, small impact) - automatic time zone changes (infrequent, big impact) - users manually changing system time (infrequent, big impact) and is therefore preferred over time.time when measuring relative times (of a program). Smaller improvements: - Remove __init__ with unnecessary instance attribute assignment (time to load the extension itself is now representative due to explicit start() call) - Use __slots__ for lower memory consumption of class instance(s) - Simplify stop(), reducing the amount of checks, instance attribute lookups and variable assignments
1 parent 23963fc commit 8a71757

1 file changed

Lines changed: 6 additions & 11 deletions

File tree

autotime/__init__.py

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from __future__ import print_function
22

3-
import time
3+
from time import monotonic
44

55
from IPython.core.magics.execution import _format_time as format_delta
66

@@ -13,26 +13,21 @@ class LineWatcher(object):
1313
-----
1414
* Register the `start` and `stop` methods with the IPython events API.
1515
"""
16-
17-
def __init__(self):
18-
self.start_time = 0.0
16+
__slots__ = ['start_time']
1917

2018
def start(self):
21-
self.start_time = time.time()
19+
self.start_time = monotonic()
2220

2321
def stop(self):
24-
stop_time = time.time()
25-
26-
if self.start_time:
27-
diff = stop_time - self.start_time
28-
assert diff >= 0
29-
print('time: {}'.format(format_delta(diff)))
22+
delta = monotonic() - self.start_time
23+
print('time: {}'.format(format_delta(delta)))
3024

3125

3226
timer = LineWatcher()
3327

3428

3529
def load_ipython_extension(ip):
30+
timer.start()
3631
ip.events.register('pre_run_cell', timer.start)
3732
ip.events.register('post_run_cell', timer.stop)
3833

0 commit comments

Comments
 (0)