Last active
November 22, 2016 06:40
-
-
Save walsvid/1ea952e5c42baf0381ae337f3cb3b178 to your computer and use it in GitHub Desktop.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #! /usr/bin/env python | |
| # -*- coding: utf-8 -*- | |
| 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