How to time Django queries
Asked Answered
O

4

13

I've always used Python's timeit library to time my little Python programs. Now I'm developing a Django app and I was wondering how to time my Django functions, especially queries.

For example, I have a def index(request) in my views.py which does a bunch of stuff when I load the index page. How can I use timeit to time this particular function without altering too much my existing functions?

Overcasting answered 9/12, 2010 at 17:27 Comment(0)
C
6

The debug toolbar is what you want, it helps you time each of your queries.

Alternatively this snippet works too.

http://djangosnippets.org/snippets/93/

Cohobate answered 9/12, 2010 at 17:32 Comment(1)
Nice, I installed and configured debug_toolbar, it's a nice feature to have from the start.Overcasting
S
30

if your django project is in debug, you can see your database queries (and times) using:

>>> from django.db import connection
>>> connection.queries

I know this won't satisfy your need to profile functions, but hope it helps for the queries part!

Stampede answered 9/12, 2010 at 17:32 Comment(0)
C
6

The debug toolbar is what you want, it helps you time each of your queries.

Alternatively this snippet works too.

http://djangosnippets.org/snippets/93/

Cohobate answered 9/12, 2010 at 17:32 Comment(1)
Nice, I installed and configured debug_toolbar, it's a nice feature to have from the start.Overcasting
F
6

The best way you can get is by using Debug Toolbar, you will also get some additional functionalities for Query optimization, which will help you to optimize your db query.

Here is another solution, You can use connection.queries. This will return the SQL command has been made for the command which was executed just before the connect.queries command. You can the reset_queries after getting the time of the previous query by using reset_queries(). Using reset_queries() is not mandatory.

Suppose you have a Model named Device. You can measure the query time like this:

>>> from django.db import connection, reset_queries
>>> from appname.models import Device
>>> devices = Device.objects.all()
>>> connection.queries
>>> reset_queries()
Frontwards answered 21/10, 2019 at 9:17 Comment(0)
A
1

Anyone stumbling on to this checkout Sentry's approach.

https://github.com/getsentry/sentry-python/blob/master/sentry_sdk/integrations/django/__init__.py#L476

You can replace execute and executemany with your owns functions that track the time it takes for execute to return.

A simple approach is to create custom context manager that initiates a timer and on exit writes final value of the timer to an array you pass to it.

Then you can just check the array.

Ambert answered 23/8, 2021 at 3:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.