Skip to main content
 首页 » 编程设计

python之如何使用 cProfile 获得更精细的结果

2024年12月31日13jpfss

我有一个正在分析的小片段,但是 list comprehension 被列为调用中的一个项目

import fileinput 
import cProfile 
 
pr = cProfile.Profile() 
pr.enable() 
x = [float(i) for i in range(0, 10**8)] 
pr.disable() 
pr.print_stats(sort='time') 

输出:

     2 function calls in 19.769 seconds 
 
   Ordered by: internal time 
 
   ncalls  tottime  percall  cumtime  percall filename:lineno(function) 
        1   19.769   19.769   19.769   19.769 sandboxMinimalCProfile.py:6(<listcomp>) 
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects} 

是否有可能获得例如转换为 float 的成本是多少?

请您参考如下方法:

这里的问题是 float 是内置函数,因此它们不算作对分析器的调用。

您可以尝试解决它;但是,分析器在任何情况下都不是为微基准测试而设计的。相反,试试 timeit standard module :

$ python3 -m timeit 'float(1000000)' 
10000000 loops, best of 3: 0.118 usec per loop