7

I have a set of python scripts that I would like to profile with kernprof https://github.com/rkern/line_profiler but I also want to be able to run it during normal execution without kernprof.

What is an elegant way of ignoring the undefined @profile during execution without kernprof? Or any other decorator.

Example Code:

    @profile
    def hello():
        print('Testing')

    hello()

Running with:

    kernprof -l test.py

Correctly executes the profiler on @profile methods

Running with:

    python test.py 

Returns an error:

    Traceback (most recent call last):
    File "test.py", line 1, in <module>
    @profile
    NameError: name 'profile' is not defined

Would like to avoid catching this error everywhere as I want the code to execute as if @profile is a no-op when its not called with kernprof.

Thanks! -Laura

Edit: I ended up using cProfile with kcachegrind and avoiding decorators altogether.

Using cProfile results with KCacheGrind

python -m cProfile -o profile_data.pyprof run_cli.py

pyprof2calltree -i profile_data.pyprof && qcachegrind profile_data.pyprof.log
Community
  • 1
  • 1
Laura
  • 139
  • 1
  • 11

2 Answers2

9

Define a no-op decorator if not executed from kernprof:

if 'profile' not in globals():
    def profile(func):
        return func
Daniel
  • 42,087
  • 4
  • 55
  • 81
0

A variant over the method proposed by Daniel, would be to use the following one-liner, and then comment it in and out depending on your need for profiling or not:

# Optional no-op decorator, comment when you want to profile
def profile(func): return func
holroy
  • 3,047
  • 25
  • 41
  • This seems like the same answer. I was really looking for a way to test if the function decorator was defined and if not then define it without having to modify the code each time I run it. Daniel's answer satisfies those requirements. – Laura Nov 17 '15 at 01:31
  • @Laura, It is indeed a variant of the same, and I appreciate that you don't want to modify the code. However, I kind of felt like it could be nice to show this as an alternative for those wanting to have the manual control, and who does not want to check/work against the `globals` list. – holroy Nov 17 '15 at 01:34
  • instead of adding this as a separate solution consider making a comment on the original solution, something like "hey Daniel, you could put this all on one line so its easier to comment it out if you want manual control." As a standalone solution it doesn't seem very elegant to have code that is commented out in some situations as it seems like really bad style. That's my opinion. Just a suggestion and no offense intended but I would down vote this answer because I personally hate seeing commented out code in production code. – Laura Nov 17 '15 at 07:31