I am using a nice tool called https://github.com/rkern/line_profiler
To use it, you need to put a decorator @profile
at multiple places in the script to indicate which functions should be profiled. Then you execute the script via kernprof -l script_to_profile.py
Obviously, when running the script by itself via python script_to_profile.py
, the decorator is not defined and hence the script crashes.
I know how to define an identity decorator and I can pass a flag from the command line and define it in the main script depending on how the flag is set. However, I don't know how to pass the decorator definition (or the flag) to modules I load so they don't crash at the moment they are loaded. Any ideas?
def profile(func):
return func
A very simple way would be to check if something named profile
exists, and if it doesn't, then define it to be your identity decorator. Something like this.
try:
profile
except NameError:
def profile(func):
return func
You could go a little further and make sure it's something callable — probably not necessary:
import typing
try:
profile
except NameError:
profile = None
if not isinstance(profile, typing.Callable):
def profile(func):
return func
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.