[英]How to calculate execution time of a view in Django?
這是我的觀點:
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)
有什么方法可以計算 Django 中的執行時間嗎?
您可以將計時器裝飾器寫入 output 控制台中的結果
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
是的,如果您只想測量視圖 function 的執行時間,您可以使用時間模塊並注銷差異:
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)
您可以創建@timer
裝飾器來為您的視圖計時,如下所示:
# "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")
控制台輸出:
3.0174264907836914 seconds
3017.4264907836914 milliseconds
[18/Dec/2022 05:30:49] "GET /store/test_view/ HTTP/1.1" 200 9
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.