这是你list_comprehension
的,需要 10 秒。函数的参数在函数被调用之前被评估,所以如果你在函数内部进行分析,代价高昂list_comprehension
的已经完成。
例如看这个:
import time, cProfile
def func_a(a_list):
return len(a_list)
def func_b(a_list, pr):
pr.enable()
ret = len(a_list)
pr.disable()
return ret
def main():
pr = cProfile.Profile()
pr.enable()
func_a([time.sleep(x) for x in range(3)])
pr.disable()
pr.print_stats()
pr = cProfile.Profile()
func_b([time.sleep(x) for x in range(3)], pr)
pr.print_stats()
pr = cProfile.Profile()
pr.enable()
[time.sleep(x) for x in range(3)]
pr.disable()
pr.print_stats()
if __name__ == '__main__':
main()
将输出如下内容:
7 function calls in 3.006 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 tmp.py:3(func_a)
1 0.000 0.000 0.000 0.000 {len}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
1 0.000 0.000 0.000 0.000 {range}
3 3.006 1.002 3.006 1.002 {time.sleep}
2 function calls in 0.000 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 {len}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
5 function calls in 3.004 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
1 0.000 0.000 0.000 0.000 {range}
3 3.004 1.001 3.004 1.001 {time.sleep}