jtlz2
jtlz2

Reputation: 8407

Python profiling using line_profiler - clever way to remove @profile statements on-the-fly?

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?

Upvotes: 18

Views: 9523

Answers (5)

JonnyRobbie
JonnyRobbie

Reputation: 614

The other answers are correct, but those may pose an issue when trying to "prime" the script with something like kernprof -l --setup script.py script.py. Priming your script like this may be useful for example when you try to optimize your functions with numba and you don't want to bias your line timings with compiling (or loading from filesystem cache, which still has a significant overhead even with numbas cache=True param).

The issue is that the setup run noops all your @profile decorators and renders them moot for the profiling run.

I solved that by moving the try except to the actual decorator run like this:

def profile2(f):
    def s(*args, **kwargs):
        try:
            return profile(f)(*args, **kwargs)
        except NameError:
            return f(*args, **kwargs)
    return s

and decorating all my profiled function with @profile2.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1123032

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:

try:
    # Python 2
    import __builtin__ as builtins
except ImportError:
    # Python 3
    import builtins

try:
    builtins.profile
except AttributeError:
    # No line profiler, provide a pass-through version
    def profile(func): return func
    builtins.profile = profile

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:

try:
    # Python 2
    import __builtin__ as builtins
except ImportError:
    # Python 3
    import builtins

try:
    profile = builtins.profile
except AttributeError:
    # No line profiler, provide a pass-through version
    def profile(func): return func

(no assignment to builtins.profile) and use from profile_support import profile in any module that uses the @profile decorator.

Upvotes: 24

0 _
0 _

Reputation: 11494

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 that line_profiler is involved, w/o a priori knowing this.

Looking at kernprof line 199, it suffices to instantiate LineProfiler.

try:
    from line_profiler import LineProfiler
    profile = LineProfiler()
except ImportError:
    def profile(func):
        return func

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 by kernprof. This side-effect may be undesired.

Upvotes: 6

MSeifert
MSeifert

Reputation: 152695

You don't need to import __builtins__/builtins or LineProfiler at all, you can simply rely on a NameError when trying to lookup profile:

try:
    profile
except NameError:
    profile = lambda x: x

However this needs to be included in every file that uses profile, but it doesn't (permanently) alter the global state (builtins) of Python.

Upvotes: 11

ChrisP
ChrisP

Reputation: 5942

I am using the following modified version with Python 3.4

try:
    import builtins
    profile = builtins.__dict__['profile']
except KeyError:
    # No line profiler, provide a pass-through version
    def profile(func): return func

Upvotes: 1

Related Questions