Last active
May 12, 2019 12:30
-
-
Save Cologler/c0eb9592d72be367a8e17bf0d5bd3310 to your computer and use it in GitHub Desktop.
code timer for python, base on timeit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import contextlib | |
import gc | |
@contextlib.contextmanager | |
def disable_gc(): | |
if gc.isenabled(): | |
gc.disable() | |
yield | |
gc.enable() | |
else: | |
yield | |
class CodeTimer: | |
def __init__(self): | |
self._total = None | |
self._begin = None | |
@contextlib.contextmanager | |
def begin(self): | |
if self._begin is not None: | |
raise RuntimeError | |
pfc = time.perf_counter | |
with disable_gc(): | |
self._begin = pfc() | |
yield self | |
self._total = pfc() - self._begin | |
@property | |
def time(self): | |
if self._total is None: | |
raise RuntimeError | |
return self._total | |
def used(self): | |
if self._begin is None: | |
raise RuntimeError | |
return time.perf_counter() - self._begin |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment