Skip to content

Instantly share code, notes, and snippets.

@renejahn
Created October 4, 2017 08:53
Show Gist options
  • Save renejahn/addd93337c9d5c4dc9800bb8f9a461a6 to your computer and use it in GitHub Desktop.
Save renejahn/addd93337c9d5c4dc9800bb8f9a461a6 to your computer and use it in GitHub Desktop.
can be used for timing python code execution
import time
class TimedExecution(object):
def __init__(self, enter_message=None, exit_message=None):
self.enter_message = enter_message
self.exit_message = exit_message
def __enter__(self):
if self.enter_message:
print self.enter_message
self.begin = time.time()
def __exit__(self, exc_type, exc_val, exc_tb):
exec_time = time.time() - self.begin
if self.exit_message:
print 'Execution took {s} seconds. {msg}'.format(s=exec_time, msg=self.exit_message)
else:
print 'Execution took {s} seconds.'.format(s=exec_time)
# Usage example
with TimedExecution(enter_message='Beginning to sleep.', exit_message='Woke up.'):
time.sleep(3)
print 'sleeping'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment