如何计算 Django 中视图的执行时间?
how can you 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 中的执行时间吗?
是的,如果您只想测量视图函数的执行时间,您可以只使用时间模块并记录差异:
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)
你可以写一个定时器装饰器在你的控制台输出结果
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
这是我的观点:
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 中的执行时间吗?
是的,如果您只想测量视图函数的执行时间,您可以只使用时间模块并记录差异:
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)
你可以写一个定时器装饰器在你的控制台输出结果
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