pyutils / line_profiler

Line-by-line profiling for Python
Other
2.57k stars 118 forks source link

Draft: mark function to profile from the CLI #190

Closed Carreau closed 1 month ago

Carreau commented 1 year ago

This is a draft that allows to profile some function without having to modify the source.

It does so by inserting an importhook that will be active only for module/function pairs that are passed on the command line, and for the given functions it will insert the @profile decorator.

The code is not the best, but I'm mostly opening this to get feedback as to whether you believe this is an interesting possibility to push forward, or if it something I should just use for me locally/publish as a separate package.

You can try it with for example

$ python -m kernprof -l  --prof bar:f -v line_profiler/foo.py
$ cat foo.py
from bar import f, g

def main():
    for i in range(60):
        f()
        g()

main()
$ cat bar.py
import time

def f():
    5
    time.sleep(0.001)
    7

def g():
    pass

And you will get the following without having to add the decorator.

Timer unit: 1e-06 s

Total time: 0.081675 s
File: /Users/bussonniermatthias/dev/line_profiler/bar.py
Function: f at line 3

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     3                                           def f():
     4        60         37.0      0.6      0.0      5
     5        60      81574.0   1359.6     99.9      time.sleep(0.001)
     6        60         64.0      1.1      0.1      7