首页 > 解决方案 > 如何对 Python 代码源的反汇编表示进行计时

问题描述

到目前为止,当我想检查与非常相似的方法相比可能导致某种代码运行得更快的原因时,我正在使用该dis模块。但是,比较原因的进一步步骤基本上是添加/删除行。

有没有更复杂的方法来实际列出重犯者是什么?

标签: python

解决方案


你想分析什么样的代码?如果要分析纯python代码。您可以使用profile. 例如:

import cProfile

cProfile.run("x=1")

或者你可以运行一个函数:cProfile.run("function()")

然后它将向您显示如下内容:

         4 function calls in 0.013 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.013    0.013    0.013    0.013 <ipython-input-7-8201fb940887>:1(fun)
        1    0.000    0.000    0.013    0.013 <string>:1(<module>)
        1    0.000    0.000    0.013    0.013 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

推荐阅读