Login

Quick line profiler decorator

Author:
ibestuzhev
Posted:
May 12, 2015
Language:
Python
Version:
1.7
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

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.