pythonpython-3.xdjangodjango-viewsexecution-time

How to calculate execution time of a view in Django?


This is my view:

def post_detail(request, year, month, day, slug):
post = get_object_or_404(models.Post, slug=slug, status='published',
                         publish__year=year, publish__month=month,
                         publish__day=day)

comment_form = forms.CommentForm()
comments = post.comments.filter(active=True)

context = {
    'comments': comments,
    'post': post,
    'comment_form': comment_form,
}
return render(request, 'blog/post_detail.html', context)

Is there any way to calculate time of execution in Django ?


Solution

  • You can write a timer decorator to output the results in your console

    from functools import wraps
    import time
    
    def timer(func):
        """helper function to estimate view execution time"""
    
        @wraps(func)  # used for copying func metadata
        def wrapper(*args, **kwargs):
            # record start time
            start = time.time()
    
            # func execution
            result = func(*args, **kwargs)
            
            duration = (time.time() - start) * 1000
            # output execution time to console
            print('view {} takes {:.2f} ms'.format(
                func.__name__, 
                duration
                ))
            return result
        return wrapper
    
    @timer
    def your_view(request):
        pass