I want to use the excellent line_profiler, but only some of the time. To make it work I add
@profile
before every function call, e.g.
@profile
def myFunc(args):
blah
return
and execute
kernprof.py -l -v mycode.py args
But I don't want to have to put the @profile
decorators in by hand each time, because most of the time I want to execute the code without them, and I get an exception if I try to include them, e.g.
mycode.py args
Is there a happy medium where I can dynamically have the decorators removed based on some condition switch/argument, without having to do things manually and/or modify each function too much?
I am using the following modified version with Python 3.4
You don't need to import
__builtins__
/builtins
orLineProfiler
at all, you can simply rely on aNameError
when trying to lookupprofile
:However this needs to be included in every file that uses
profile
, but it doesn't (permanently) alter the global state (builtins) of Python.Instead of removing the
@profile
decorator lines, provide your own pass-through no-op version.You can add the following code to your project somewhere:
Import this before any code using the
@profile
decorator and you can use the code with or without the line profiler being active.Because the dummy decorator is a pass-through function, execution performance is not impacted (only import performance is every so lightly affected).
If you don't like messing with built-ins, you can make this a separate module; say
profile_support.py
:(no assignment to
builtins.profile
) and usefrom profile_support import profile
in any module that uses the@profile
decorator.A comment that grew to become a variant of @Martijin Pieters answer.
I prefer not to involve
__builtin__
at all. W/o a comment, it would be practically impossible for someone else to guess thatline_profiler
is involved, w/o a priori knowing this.Looking at
kernprof
line 199, it suffices to instantiateLineProfiler
.Importing (explicit) is better than globally modifying
builtins
(implicit). If the profiling decorators are permanent, then their origin should be clear in the code itself.In presence of
line_profiler
, the above approach will wrap the decorated functions with profilers on every run, irrespective of whether run bykernprof
. This side-effect may be undesired.