Skip to content

Instantly share code, notes, and snippets.

@amancevice
Last active October 25, 2016 13:43
Show Gist options
  • Save amancevice/8a28df4a64f95451395b4a13eee1a410 to your computer and use it in GitHub Desktop.
Save amancevice/8a28df4a64f95451395b4a13eee1a410 to your computer and use it in GitHub Desktop.
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