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
To create a decorator function in Python, I create an outer function that takes a function as an argument. There is also an inner function that wraps around the decorated function. To use a decorator ,you attach it to a function like you see in the code below.
You can define Python function optional arguments by specifying the name of an argument followed by a default value when you declare a function. You can also use the **kwargs method to accept a variable number of arguments in a function.
Needless to say, Python's decorators are incredibly useful. Not only can they be used to slow down the time it takes to write some code, but they can also be incredibly helpful at speeding up code. Not only are decorators incredibly useful when you find them about, but it is also a great idea to write your own.
Define a no-op decorator if not executed from kernprof:
if 'profile' not in globals():
def profile(func):
return func
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With