Skip to content

Instantly share code, notes, and snippets.

@willmcgugan
Created June 18, 2012 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willmcgugan/2948552 to your computer and use it in GitHub Desktop.
Save willmcgugan/2948552 to your computer and use it in GitHub Desktop.
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