Created
May 18, 2023 20:39
-
-
Save camflan/78c6d920804f294671284114316a2cd3 to your computer and use it in GitHub Desktop.
Handy decorators for timing and counting django db queries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import functools | |
import time | |
from django.db import connection | |
def timer(func): | |
@functools.wraps(func) | |
def wrapper_timer(*args, **kwargs): | |
tic = time.perf_counter() | |
value = func(*args, **kwargs) | |
toc = time.perf_counter() | |
elapsed_time = toc - tic | |
print(f"[{func.__name__}] elapsed time: {elapsed_time * 1000:0.2f} ms") | |
return value | |
return wrapper_timer | |
def query_count(func): | |
@functools.wraps(func) | |
def wrapper_timer(*args, **kwargs): | |
initial_query_count = len(connection.queries) | |
value = func(*args, **kwargs) | |
print( | |
f"[{func.__name__}] queries executed: " | |
f"{len(connection.queries) - initial_query_count}" | |
) | |
return value | |
return wrapper_timer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment