Skip to content

Instantly share code, notes, and snippets.

@vsmelov
Last active August 30, 2018 11:14
Show Gist options
  • Save vsmelov/ce39b0ff849ae60944441f476c8ea6e6 to your computer and use it in GitHub Desktop.
Save vsmelov/ce39b0ff849ae60944441f476c8ea6e6 to your computer and use it in GitHub Desktop.
Удобный контекстный менеджер для засекания исполнения чего-либо
from time import time
class Timer:
def __init__(self, begin=None, end=None):
self.begin = begin
self.end = end
def __enter__(self):
self.begin = time()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.end = time()
@property
def t(self):
if self.end is None:
return time() - self.begin
else:
return self.end - self.begin
def __str__(self):
return '{:.2f}'.format(self.t)
def __repr__(self):
return 'Timer(begin={}, end={})'.format(self.begin, self.end)
class TimerLog(Timer):
def __init__(self, log='executed at {t}sec', **kwargs):
super().__init__(**kwargs)
self.log = log
def __exit__(self, exc_type, exc_val, exc_tb):
super().__exit__(exc_type, exc_val, exc_tb)
print(self.log.format(t=self.t))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment