Django生产缓慢,测试速度快

时间:2013-08-19 02:29:28

标签: django performance

我们使用Django托管的网站在生产服务器上非常慢:数据库访问速度似乎很慢(Mysql),下载文件很慢(我尝试过X-Sendfile,但没有影响)。

使用基于this snippet的内容进行性能分析,最重的:

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
 11570    0.577    0.000    0.577    0.000 /var/lib/python-support/python2.6/MySQLdb/times.py:43(DateTime_or_None)
  5786    0.500    0.000    0.617    0.000 /usr/local/lib/python2.6/dist-packages/django/db/models/base.py:244(__init__)
  5796    0.205    0.000    0.576    0.000 /usr/local/lib/python2.6/dist-packages/django/forms/widgets.py:411(render_option)
     8    0.190    0.024    1.014    0.127 /var/lib/python-support/python2.6/MySQLdb/cursors.py:282(_fetch_row)

21.6%   0.577 /var/lib/python-support/python2.6/MySQLdb/times.py
19.4%   0.520 /usr/local/lib/python2.6/dist-packages/django/db/models/base.py
 9.5%   0.253 /usr/local/lib/python2.6/dist-packages/django/forms/widgets.py
 7.4%   0.199 /var/lib/python-support/python2.6/MySQLdb/cursors.py

33.0%   0.882 /var/lib/python-support/python2.6/MySQLdb
32.6%   0.873 /usr/local/lib/python2.6/dist-packages/django/db
15.4%   0.413 /usr/local/lib/python2.6/dist-packages/django/forms
10.5%   0.280 /usr/local/lib/python2.6/dist-packages/django/utils

以上调用是在管理页面上运行的。

我能做什么:   - 更新mysql   - 更新整个django框架(仍在1.1上运行)

但我认为,必须有其他原因,为什么这么慢。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

它应该只在生产服务器上第一次变慢,但是对于页面的以下访问,例如django memcached,行为应该是不同的。

 install django-memcached on production server

 settings.py:

 CACHE_BACKEND ="memcached://127.0.0.1:11211/" # change the IP to the server IP
 CACHE_TIMEOUT =60*60     #to keep items in the cache it's up to you

 # if you wish to cache some data which are permanently in high demand 
 views.py :
 from django.core.cache import cache
 from project.settings import CACHE_TIMEOUT
 # example of how to use the cache in the methods
 def method(request):
    model_cache_key = request.path
c = cache.get(model_cache_key)
if not c:
    c=get_object_or_404(model,id=self.id)
    cache.set(model_cache_key,c,CACHE_TIMEOUT)
#END OF USE CACHE HERE
foo=c.modelname_set.all()
    # more code here
    return #whatever you want

答案 1 :(得分:0)

您可以在配置文件输出中看到,MySQLdb的函数DateTime_or_None花费了大量时间。

我最近遇到了同样的问题,似乎在MySQL中使用DATETIME字段并不是一个好主意,特别是对于python,因为非常慢且通常不必要的转换为python datetime类型

我找到了一些关于它的文章:

嗯,我不确定丢弃DATETIME是否是正确的解决方案,可能从MySQLdb更改为其他MySQL适配器将有助于提高性能。