Created
September 24, 2015 00:55
-
-
Save doctaphred/09700198787da12de989 to your computer and use it in GitHub Desktop.
simple Python profiler
This file contains 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
""" | |
$ python -i simple_profiler.py | |
>>> mark() | |
2015-09-23 20:49:30.993140: Starting profiler [default] | |
>>> mark('before crazy stuff') | |
2015-09-23 20:49:34.855766: Profiler [default], mark #1 (before crazy stuff): took 3.862e+00s | |
>>> mark('after crazy stuff') | |
2015-09-23 20:49:40.047713: Profiler [default], mark #2 (after crazy stuff): took 5.192e+00s | |
>>> mark() | |
2015-09-23 20:49:46.805728: Profiler [default], mark #3: took 6.758e+00s | |
""" | |
from __future__ import print_function | |
from datetime import datetime | |
from itertools import count | |
import time | |
def create_profiler(name): | |
print('{}: Starting profiler {}'.format(datetime.now(), name)) | |
for i in count(1): | |
start_time = time.time() | |
mark = yield | |
end_time = time.time() | |
if mark is None: | |
mark = '' | |
else: | |
mark = ' ({})'.format(mark) | |
print('{}: Profiler {}, mark #{}{}: took {:.3e}s'.format( | |
datetime.now(), name, i, mark, end_time - start_time)) | |
default_profiler = create_profiler('[default]') | |
def mark(name=None): | |
default_profiler.send(name) | |
class Profiler(object): | |
def __init__(self, name): | |
self._profiler = create_profiler(name) | |
next(self._profiler) | |
def mark(self, name=None): | |
self._profiler.send(name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment