Skip to content

Instantly share code, notes, and snippets.

@camflan
Created May 18, 2023 20:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save camflan/78c6d920804f294671284114316a2cd3 to your computer and use it in GitHub Desktop.
Save camflan/78c6d920804f294671284114316a2cd3 to your computer and use it in GitHub Desktop.
Handy decorators for timing and counting django db queries
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