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}