How to calculate execution time of a view in Django?

Question:

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 ?

Asked By: Farid Darabi

||

Answers:

yes if you just want to measure execution time of view function you could just use the time module and log out the difference:

import time
def post_detail(request, year, month, day, slug):
    startT = time.time()
    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,
    }
    print(f'function time: {time.time() - startT}ms')
    return render(request, 'blog/post_detail.html', context)
Answered By: Yosef Salmalian

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
Answered By: minglyu

You can create @timer decorator to time your views as shown below:

# "store/views.py"

from time import time
from time import sleep
from django.http import HttpResponse

def timer(func): # Here
    def core(*args, **kwargs):
        start = time()
        result = func(*args, **kwargs)
        end = time()
        print(end - start, "seconds")
        print((end - start)*1000, "milliseconds")
        return result
    return core

@timer # Here
def test_view(request):
    sleep(1)
    sleep(1)
    sleep(1)
    return HttpResponse("Test_view")

Output on console:

3.0174264907836914 seconds
3017.4264907836914 milliseconds
[18/Dec/2022 05:30:49] "GET /store/test_view/ HTTP/1.1" 200 9
Answered By: Kai – Kazuya Ito