Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Timer decorator
from contextlib import contextmanager
from time import time, mktime
from datetime import datetime
@contextmanager
def timer(msg="elapsed", ms=False, write_file=None):
now = datetime.now()
start = time()
yield
taken = (time() - start)
if ms:
print "%s: %.2fms" % (msg, taken * 1000)
else:
print "%s: %.2fs" % (msg, taken)
if write_file is not None:
import socket
hostname = socket.gethostname()
with open(write_file, 'a+') as f:
f.write('%s,%.2f,"%s","%s"\n' % (now.ctime(), taken, msg, hostname))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.