【问题标题】:How to profile a Django custom management command exclusively如何专门分析 Django 自定义管理命令
【发布时间】:2009-11-06 11:54:56
【问题描述】:

我想分析一个相对 CPU 密集型的自定义管理命令(使用 PIL 渲染图像)。当我使用以下命令时,我的分析结果中会出现各种 Django 模块(管理员、ORM 等):

python -m cProfile manage.py testrender

我已经删除了所有可能导入 Django 的导入,但我猜以下是罪魁祸首:

from django.core.management.base import BaseCommand, CommandError

有没有办法过滤掉cProfile 结果? (只显示文件名,没有路径)或者,有没有其他方法可以从分析中排除/包含相应的模块/包?

【问题讨论】:

  • @Geo grep 没有太大帮助,因为没有给出文件路径。只打印文件名。现在假设我有想要分析的 utils.py 并且在 Django 的某个地方还有另一个 utils.py。

标签: python django profiling


【解决方案1】:

我通过以下方式解决了这个问题:

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

这样更好。

【讨论】:

【解决方案2】:

在自己的模块中将 PIL 功能分离到自己的函数/类中,然后从您的管理命令中导入。然后,您可以独立于 Django 测试/分析 PIL 功能。

【讨论】:

  • 就像你说的,在一个单独的模块中并从命令中导入。问题是如何独立分析。我什至不需要超级隔离,我只是不想要 50 个相关条目和 950 个不相关条目。你想让我发布一些代码吗?
  • 我不明白问题出在哪里。如果您将其分离到自己的模块中(根本没有对 Django 的引用),您就不能编写一个简单的测试工具来运行该模块并对其进行分析吗?我看不出你的配置文件输出中会有任何 Django 代码。
  • 您的意思是创建另一个可执行文件?那将是一个解决方案。我只是想知道是否有可能,使用 Django 管理命令。
【解决方案3】:

如果我找不到任何答案。 Gprof2Dot as explained here 是可以接受的黑客攻击。

它不会过滤掉我不感兴趣的模块,但希望它能更容易地检查结果,以直观地分离我的代码和 Django 模块。

【讨论】:

    猜你喜欢
    • 2016-03-28
    • 1970-01-01
    • 2012-08-28
    • 2019-09-24
    • 2016-06-08
    • 2018-06-19
    • 2012-03-26
    • 2021-03-09
    • 2011-04-11
    相关资源
    最近更新 更多