Instantly share code, notes, and snippets.

What would you like to do?
Simple Timer context manager. It will take care of starting the timer when your code block begins execution and stopping the timer when your code block ends.
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# @Author:
# @Last Modified time: 2016-06-12 23:46:06
from time import clock
class Timer(object):
def __init__(self, verbose=False):
self.verbose = verbose
def __enter__(self):
self.start = clock()
return self
def __exit__(self, *args):
self.end = clock()
self.secs = self.end - self.start
self.msecs = self.secs * 1000 # millisecs
if self.verbose:
print 'elapsed time: %f ms' % self.msecs
# Use case
if __name__ == "__main__":
orignal_str = "Profiling a Python program is doing a dynamic analysis"\
"that measures the execution time of the program and"\
"everything that compose it."
with Timer() as t:
replace_str = ""
for i, char in enumerate(orignal_str * 10000):
c = char if char != " " else "-"
replace_str += c
print t.secs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment