Skip to content

Instantly share code, notes, and snippets.

@Cologler
Last active May 12, 2019 12:30
Show Gist options
  • Save Cologler/c0eb9592d72be367a8e17bf0d5bd3310 to your computer and use it in GitHub Desktop.
Save Cologler/c0eb9592d72be367a8e17bf0d5bd3310 to your computer and use it in GitHub Desktop.
code timer for python, base on timeit
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