在使用django在web项目开发中避免不了会进行性能优化,最近特意总结了一些我用到过的性能优化方法。都是实际开发过程中非常有用的技巧,希望能够对大家有所帮助。
性能分析工具
cprofile
from cProfile import Profile
import pstats
prof = Profile()
prof.enable()
# 运行函数
run_func()
prof.create_stats()
p = pstats.Stats(prof)
p.print_callees()
运行程序,可以看到每行代码执行所花费的时间
line_profiler
在函数名上添加@profile装饰器,然后使用
kernprof -l -v loopdemo.py
django-debug-toolbar
Django Debug Toolbar是Django开发中必备利器,可以帮助开发者快速了解项目的整体信息以及每个页面包括sql信息,http相关信息.
pip install django-debug-toolbar
-
打开项目文件夹settings.py 文件, 把"debug_toolbar"加到INSTALLED_APP里去。
-
打开项目文件夹里的urls.py, 把debug_toolbar的urls加进去。
from django.conf import settings
from django.conf.urls import include, url
from django.urls import include, path
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
path('__debug__/', include