Measure the execution time of a function or endpoint in Flask
For better and more precise measurement of execution time in Django, you can use a custom middleware or a decorator. Middleware is ideal for measuring the total request-response cycle, while a decorator is best for timing a specific function or view.
Using a Custom Middleware
A custom middleware is the most robust and centralized way to measure the execution time of every request in a Django application. It measures the total time from when Django receives a request to when it sends a response.
1. Create a middleware.py
File
In one of your Django apps, create a middleware.py
file. This is a common convention for custom middleware.
import time
class ExecutionTimeMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
start_time = time.perf_counter()
response = self.get_response(request)
end_time = time.perf_counter()
execution_time_ms = (end_time - start_time) * 1000
# Log the execution time
print(f"Request to '{request.path}' took {execution_time_ms:.4f} ms")
# Add the time to the response headers (optional)
response["X-Process-Time-Ms"] = str(execution_time_ms)
return response
time.perf_counter()
is used for its high precision, as it provides a monotonic clock that is not affected by system time changes.
2. Register the Middleware
Next, you need to add this new middleware to your Django project's settings. Open settings.py
and add the middleware to the MIDDLEWARE
list. It's best to place it near the top to ensure it wraps around most of the other middleware.
# settings.py
MIDDLEWARE = [
# ... other middleware
'your_app_name.middleware.ExecutionTimeMiddleware',
# ... other middleware
]
Using a Decorator for a Specific View
If you only need to measure the performance of a particular view, a decorator is a more targeted solution.
1. Create a decorators.py
File
In one of your Django apps, create a file named decorators.py
to store your custom decorator.
import time
import functools
def measure_execution_time(view_func):
"""A decorator to measure the execution time of a Django view."""
@functools.wraps(view_func)
def wrapper(request, *args, **kwargs):
start_time = time.perf_counter()
response = view_func(request, *args, **kwargs)
end_time = time.perf_counter()
execution_time_ms = (end_time - start_time) * 1000
print(f"'{view_func.__name__}' executed in {execution_time_ms:.4f} ms")
return response
return wrapper
2. Apply the Decorator to a View
Now you can apply this decorator to any of your function-based or class-based views.
# views.py
from django.shortcuts import render
from .decorators import measure_execution_time
@measure_execution_time
def my_view(request):
# Simulate a time-consuming task
time.sleep(0.1)
return render(request, 'my_template.html')