Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reducing boilerplate #249

Open
beasteers opened this issue Jul 2, 2023 · 2 comments
Open

Reducing boilerplate #249

beasteers opened this issue Jul 2, 2023 · 2 comments

Comments

@beasteers
Copy link

beasteers commented Jul 2, 2023

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
@joerick
Copy link
Owner

joerick commented Jul 3, 2023

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.

@joerick
Copy link
Owner

joerick commented Jul 3, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants