Last active
May 5, 2020 11:24
-
-
Save Toshakins/dd06265aea5977f688d790433f139b54 to your computer and use it in GitHub Desktop.
Python Benchmark Decorator and Context Manager
This file contains 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 gc | |
import time | |
def readable_time(): | |
return time.strftime('%Y %b %d %H:%M:%S +0000', | |
time.gmtime(time.time())) | |
class Timer: | |
def __init__(self, scope): | |
self.scope = scope or '====' | |
def __enter__(self): | |
self.gcold = gc.isenabled() | |
gc.disable() | |
print(f'{readable_time()} {self.scope} started') | |
self.start = time.perf_counter() | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
self.end = time.perf_counter() | |
if self.gcold: | |
gc.enable() | |
print(f'{readable_time()} {self.scope} elapses {self.end - self.start:.5f} seconds') | |
def __call__(self, fn): | |
def cb(*args, **kwargs): | |
with self: | |
fn(*args, **kwargs) | |
return cb | |
@Timer('===') | |
def waiter(x): | |
time.sleep(x) | |
if __name__ == '__main__': | |
waiter(2) | |
with Timer('++++'): | |
time.sleep(3) | |
### Output: | |
### 2020 May 05 11:24:00 +0000 === started | |
### 2020 May 05 11:24:02 +0000 === elapses 2.00415 seconds | |
### 2020 May 05 11:24:02 +0000 ++++ started | |
### 2020 May 05 11:24:05 +0000 ++++ elapses 3.00135 seconds |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment