Last active
October 25, 2016 13:43
-
-
Save amancevice/8a28df4a64f95451395b4a13eee1a410 to your computer and use it in GitHub Desktop.
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
from datetime import datetime | |
from time import sleep | |
class Timer(object): | |
""" ActiveRecord Migration-style timer using context management. """ | |
def __init__(self, name): | |
self.name = name | |
self.start = datetime.utcnow() | |
@property | |
def label(self): | |
return self.start.strftime("%Y%m%d%H%M%S") | |
@property | |
def delta(self): | |
return round((datetime.utcnow() - self.start).total_seconds(), 4) | |
def __enter__(self): | |
print("== {} {} ".format(self.label, self.name).ljust(79, "=")) | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
print( | |
"== {} {} ({}s) " | |
.format(self.label, self.name, self.delta) | |
.ljust(79, "=")) | |
with Timer("My Context") as timer: | |
print("-- do_something") | |
sleep(2) | |
print(" -> 2.0000s") | |
# == 20161025134304 My Context ================================================== | |
# -- do_something | |
# -> 2.0000s | |
# == 20161025134304 My Context (2.0044s) ======================================== |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment