如何专门对Django自定义管理命令进行性能分析
我想要对一个自定义的管理命令进行性能分析,这个命令比较耗CPU资源(它使用PIL来渲染图像)。当我使用下面的命令时,我在性能分析的结果中看到各种Django模块(比如admin、ORM等):
python -m cProfile manage.py testrender
我已经去掉了所有可能会导入Django的部分,但我猜下面的代码可能是问题所在:
from django.core.management.base import BaseCommand, CommandError
有没有办法过滤掉cProfile
的结果?(只显示文件名,没有路径)或者,有没有其他方法可以在性能分析中排除或包含特定的模块/包?
3 个回答
1
把PIL的功能单独放到一个函数或类里,并放在一个单独的模块中。然后在你的管理命令中导入这个模块。这样你就可以不依赖Django,单独测试或分析PIL的功能了。
20
我用以下方法解决了这个问题:
from cProfile import Profile
from django.core.management.base import BaseCommand
class Command(BaseCommand):
...
def _handle(self, *args, **options):
# Actual code I want to profile
pass
def handle(self, *args, **options):
if options['profile']:
profiler = Profile()
profiler.runcall(self._handle, *args, **options)
profiler.print_stats()
else:
self._handle(*args, **options)
这样就可以在_handle
的范围内收集性能统计数据。所以,不用像这样:
python -m cProfile manage.py testrender
我需要运行:
python manage.py testrender --profile
这样做甚至更好。