Really simple Django view function timer decorator

08 December 2017   2 comments   Python, Django

Mind that age!

This blog post is 4 years old! Most likely, its content is outdated. Especially if it's technical.

I use this sometimes to get insight into how long some view functions take. Perhaps you find it useful too:

def view_function_timer(prefix='', writeto=print):

    def decorator(func):
        def inner(*args, **kwargs):
                t0 = time.time()
                return func(*args, **kwargs)
                t1 = time.time()
                    'View Function',
                    '({})'.format(prefix) if prefix else '',
                    '{:.2f}ms'.format(1000 * (t1 - t0)),
        return inner

    return decorator

And to use it:

from wherever import view_function_timer

def homepage(request, thing):
    return render(request, template, context)

And then it prints something like this:

View Function  homepage ('valueofthing',) Took 23.22ms http://localhost:8000/home/valueofthing

It's useful when you don't want a full-blown solution to measure all view functions with a middleware or something.
It can be useful also to see how a cache decorator might work:

from django.views.decorators.cache import cache_page
from wherever import view_function_timer

@view_function_timer('possibly cached')
@cache_page(60 * 60 * 2)  # two hours cache
@view_function_timer('not cached')
def homepage(request, thing):
    return render(request, template, context)

That way you can trace that, with tail -f or something, to see how/if the cacheing decorator works.

There are many better solutions that are more robust but might be a bigger investment. For example, I would recommend markus which, if you don't have a statsd server you can configure to call the timings.


Chris Adams

It might be neat to add a Server-Timing header ( on the response so the values could show up in the Chrome Developer Tools — e.g. see the network tab for;%20database.

Peter Bengtsson

Neat! I'm not sure what the need/use for rust might be but yeah, a decorator like this would work. Or a middleware.

Your email will never ever be published

Related posts