3

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 ?

2

3 Answers 3

9

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
1
  • thanks this is really amazing and beautiful to look at. question I have tho, can you measure the view page load time in the server? are you able to see the time it took for the user to have their page load up.
    – kaybrian
    Nov 18 at 22:06
0

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)
2
  • thanks but everytime I refresh the page , I see a new number as execution time, why everytime it is different ? for example: 0.2 , 0.4, 0.15 Jun 22, 2020 at 19:54
  • this is a very small difference (0.3 milliseconds) and it depends, most probably it is the Operating System scheduler waiting in blocked process queue when waiting for I/O, a very simple expression for a very complicated and wide concept in Operating Systems.
    – YosSaL
    Jun 23, 2020 at 9:04
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.