Check running time per line in python

时光毁灭记忆、已成空白 提交于 2020-01-03 17:45:09

问题


I've written a Python script, but running it is taking a lot longer than I had anticipated, and I've no obvious candidate for particuklar lines in the script taking up runtime.

Is there anything I can put in my code to check how long its taking to run through each line?

Many thanks.


回答1:


Have you tried running python with profiling?

python -m cProfile --sort cumulative your_single_thread_script.py &> out.log

You can find more details in this question How can you profile a python script?

You can read more about the profiling utility here.




回答2:


Use a profiler such as hotshot. It's easy!

1) run your code with the profiles:

import hotshot

prof = hotshot.Profile("hotshot_stats.prof")
prof.runcall(my_function)
prof.close()

2) Read the resulting file:

from hotshot import stats

s = stats.load("hotshot_stats.prof")
s.strip_dirs()
s.sort_stats('time', 'calls')
s.print_stats(20)



回答3:


timeit is a standard module since python 2.3 take a look at the documentation for it.



来源:https://stackoverflow.com/questions/17314366/check-running-time-per-line-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!