Skip to content

Instantly share code, notes, and snippets.

@ulgens
Created August 14, 2021 19:28
Show Gist options
  • Save ulgens/d30a7ff26640e9a71991ece2bdcfe032 to your computer and use it in GitHub Desktop.
Save ulgens/d30a7ff26640e9a71991ece2bdcfe032 to your computer and use it in GitHub Desktop.
import time
from django.db import connections
def management_command_profiler(func):
"""
This decorator shows the execution time and query count of the function passed.
Output is designed to use with methods of management commands.
"""
def wrap_func(*args, **kwargs):
t1 = time.perf_counter()
q1 = sum(len(c.queries) for c in connections.all())
result = func(*args, **kwargs)
t2 = time.perf_counter()
q2 = sum(len(c.queries) for c in connections.all())
# FIXME: Add type check
self = args[0]
self.stdout.write(self.style.SUCCESS(f"Took {t2 - t1:0.2f} seconds."))
self.stdout.write(self.style.SUCCESS(f"Took {q2 - q1} queries."))
self.stdout.write("")
return result
return wrap_func
@ulgens
Copy link
Author

ulgens commented Aug 14, 2021

Took 524.19 seconds.
Took 2781 queries.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment