Login

Quick line profiler decorator

Author:
ibestuzhev
Posted:
May 12, 2015
Language:
Python
Version:
1.7
Tags:
profile decorator line_profiler
Score:
0 (after 0 ratings)

Requires line_profiler

pip install line_profiler

Will print profile info into console

@line_profiler
def my_view(request):
    context = some_quick_func()
    return some_heavy_func(context)

It does not work good when nested, so don't wrap some_heavy_func. If you want to profile also some nested call - use extra_view parameter:

@line_profiler(extra_view=[some_heavy_func])
def my_view(request):
    context = some_quick_func()
    return some_heavy_func(context)

It will profile my_view and some_heavy_func

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
def line_profiler(view=None, extra_view=None):
    import line_profiler

    def wrapper(view):
        def wrapped(*args, **kwargs):
            prof = line_profiler.LineProfiler()
            prof.add_function(view)
            if extra_view:
                [prof.add_function(v) for v in extra_view]
            with prof:
                resp = view(*args, **kwargs)
            prof.print_stats()
            return resp
        return wrapped
    if view:
        return wrapper(view)
    return wrapper

More like this

Comments

Please login first before commenting.