很好的问题我通常不会对分析器使用太多,所以这是一个很好的借口.按照这里的例子:
https://docs.python.org/2/library/profile.html#module-cProfile我编写了一个简单的分析jinja模板的例子.
import cProfile as profile
import pstats
import StringIO
import jinja2
import time
pr = profile.Profile()
def slow():
time.sleep(2)
return "Booga!"
template = jinja2.Template(r'''
{% for i in RANGE1 %}
hello world {{ i}}
{% endfor %}{% for i in RANGE2 %}
foo bar {{ i}}
{% endfor %}{{ SLOW() }}
'''
)
# here is the bit we want to profile
pr.enable()
context = {"RANGE1": range(1000000), "RANGE2":range(100), "SLOW":slow}
template.render(context)
pr.disable()
s = StringIO.StringIO()
ps = pstats.Stats(pr, stream=s).sort_stats("cumulative")
ps.print_stats()
print(s.getvalue())
这是报告的片段:
1000130 function calls in 2.448 seconds
Ordered by: cumulative time
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 2.438 2.438 /usr/local/lib/python2.7/dist-packages/jinja2/environment.py:974(render)
1 0.122 0.122 2.438 2.438 {method 'join' of 'unicode' objects}
1000104 0.315 0.000 2.317 0.000 :5(root)
1 0.000 0.000 2.002 2.002 /usr/local/lib/python2.7/dist-packages/jinja2/runtime.py:169(call)
1 0.000 0.000 2.002 2.002 profilej.py:10(slow)
1 2.002 2.002 2.002 2.002 {time.sleep}
2 0.010 0.005 0.010 0.005 {range}
1 0.000 0.000 0.000 0.000 /usr/local/lib/python2.7/dist-packages/jinja2/environment.py:1015(new_context)
1 0.000 0.000 0.000 0.000 /usr/local/lib/python2.7/dist-packages/jinja2/runtime.py:55(new_context)
1 0.000 0.000 0.000 0.000 /usr/local/lib/python2.7/dist-packages/jinja2/runtime.py:115(__init__)
3 0.000 0.000 0.000 0.000 {hasattr}
1 0.000 0.000 0.000 0.000 /usr/local/lib/python2.7/dist-packages/jinja2/_compat.py:59()
1 0.000 0.000 0.000 0.000 /usr/local/lib/python2.7/dist-packages/jinja2/nodes.py:81(__init__)
3 0.000 0.000 0.000 0.000 {getattr}
3 0.000 0.000 0.000 0.000 /usr/local/lib/python2.7/dist-packages/jinja2/runtime.py:149(resolve)
1 0.000 0.000 0.000 0.000 /usr/local/lib/python2.7/dist-packages/jinja2/runtime.py:126()
1 0.000 0.000 0.000 0.000 {callable}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
1 0.000 0.000 0.000 0.000 {method 'iteritems' of 'dict' objects}
1 0.000 0.000 0.000 0.000 {isinstance}
正如我所说,我没有太多的经验来解释Profilers的输出,但我认为在这个例子中,您可以看到该程序在time.sleep上花费了2秒钟的时间,因为slow()被调用.其余的时间被加入.我假设Jinja2是如何处理我的两个for循环.
将此示例适用于烧瓶应用程序不应太难,只需在模板生成步骤周围添加概要分析位置,并将报告写入文件.也许你甚至可以从Web应用程序中提取你的模板,并将它们配置在烧瓶之外.
我希望这是有帮助的.