Reducing boilerplate
I use this library all the time, but I find myself re-writing these convenience utilities everytime so that I can easily enable/diable profiling on long-running scripts without having to wait for them to finish.
The rationale here is that if your script takes too long to run, oftentimes you probably don't want to wait a few hours or whatever for it to finish - maybe 5 minutes is enough so you want to interrupt it but still print out the profiling info.
import functools
import contextlib
from pyinstrument import Profiler
@contextlib.contextmanager
def profile():
try:
with Profiler() as p:
yield
finally:
p.print()
def profile_func(func):
@functools.wraps(func)
def wrapper(*a, **kw):
with profile():
return func(*a, **kw)
return wrapper
Hi! Yes, it's a good idea. One I've had before but never committed to! Lots of little details to design... E.g. support different renderers, or just Console? Save to file, or just terminal? Do we return something to the program with the with block? Could that be useful.
I might have a branch somewhere locally with some thoughts, I'll see if I can dig it up.
I found that branch. The example script run looks like this:
$ python examples/context_api.py
Start.
scanning home dir...
pyinstrument ........................................
.
. Block at /Users/joerick/Projects/pyinstrument/examples/context_api.py:14
.
. 0.548 main context_api.py:7
. ├─ 0.505 _walk os.py:344
. │ [35 frames hidden] os, posixpath
. ├─ 0.024 splitext posixpath.py:117
. │ [4 frames hidden] posixpath, genericpath
. └─ 0.014 join posixpath.py:71
. [4 frames hidden] posixpath
.
.....................................................
There are 0 python files on your system.
Total size: 0.0 kB
$
I actually included a condensed readout, I suppose I was thinking that it could be hit a few times in a program's execution.