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
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)
- [Django]-Django 1.9: Should I avoid importing models during `django.setup()`?
- [Django]-File transfer between app and media server
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
- [Django]-Django Internationalization—compilemessages error:AttributeError: module 'locale' has no attribute 'normalize'
- [Django]-Can I serve one django app from 2 different apache vhosts?
Source:stackexchange.com