如何为 Django 查询计时
我一直使用 Python 的 timeit
库来为我的小 Python 程序计时。 现在我正在开发一个 Django 应用程序,我想知道如何对 Django 函数(尤其是查询)进行计时。
例如,我的views.py中有一个def index(request),当我加载索引页面时,它会执行很多操作。 如何使用 timeit
为该特定函数计时,而不需要过多改变现有函数?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您的 django 项目正在调试,您可以使用以下命令查看数据库查询(和时间):
我知道这不能满足您分析功能的需求,但希望它对查询部分有所帮助!
if your django project is in debug, you can see your database queries (and times) using:
I know this won't satisfy your need to profile functions, but hope it helps for the queries part!
调试工具栏就是您想要的,它可以帮助您为每个查询计时。
或者这个片段也可以工作。
http://djangosnippets.org/snippets/93/
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/
最好的方法是使用 调试工具栏,您还将获得一些附加功能用于查询优化,这将帮助您优化数据库查询。
这是另一种解决方案,您可以使用
connection.queries
。这将返回已为connect.queries
命令之前执行的命令创建的 SQL 命令。您可以在使用reset_queries()
获取上一个查询的时间后重置_queries。使用reset_queries()
不是强制的。假设您有一个名为设备的模型。您可以这样测量查询时间:
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 theconnect.queries
command. You can the reset_queries after getting the time of the previous query by usingreset_queries()
. Usingreset_queries()
is not mandatory.Suppose you have a Model named Device. You can measure the query time like this:
任何偶然发现此结账哨兵方法的人。
https://github.com/ getsentry/sentry-python/blob/master/sentry_sdk/integrations/django/__init__.py#L476
您可以将
execute
和executemany
替换为您自己的函数跟踪执行返回所需的时间。一种简单的方法是创建自定义上下文管理器,该管理器启动计时器并在退出时将计时器的最终值写入您传递给它的数组。
然后你就可以检查数组了。
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
andexecutemany
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.