Skip to content

Instantly share code, notes, and snippets.

@dvdotsenko
Last active December 21, 2015 20:38
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 dvdotsenko/6362254 to your computer and use it in GitHub Desktop.
Save dvdotsenko/6362254 to your computer and use it in GitHub Desktop.
Python execution timer to be used over `with` statement.
import datetime as datetime_module
import time
class Timer:
def __init__(self, label=None):
self.label = '%s : ' % (label or 'no label provided')
return
def __enter__(self):
self.start = datetime_module.datetime.utcnow()
self.start_cpu = time.clock()
return self
def __exit__(self, *args):
end_cpu = time.clock()
end = datetime_module.datetime.utcnow()
print (self.label or '') + "CPU time is %s seconds" % (end_cpu - self.start_cpu)
print (self.label or '') + "Elapsed time is %s seconds" % (end - self.start).total_seconds()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment