[Python]cProfile

実行されたPythonプログラム内の各関数で処理にどのくらいの時間がかかっているかがわかる。

# test.py
import time
def main2():
    time.sleep(2)

def main():
    time.sleep(0.5)
    main2()

if __name__ == "__main__":
    main()
python -m cProfile test.py

#          7 function calls in 2.501 seconds

#    Ordered by: standard name

#    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
#         1    0.000    0.000    2.501    2.501 tera.py:1(<module>)
#         1    0.000    0.000    2.000    2.000 tera.py:2(main2)
#         1    0.000    0.000    2.501    2.501 tera.py:5(main)
#         1    0.000    0.000    2.501    2.501 {built-in method builtins.exec}
#         2    2.501    1.250    2.501    1.250 {built-in method time.sleep}
#         1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

main2()では2秒、main()では0.5秒+2秒で2.5秒かかっていることがわかる。