For any particular bit of code, is there a way to easily get a breakdown of how long it took each line to execute?
-
2[26.4 The Python Profilers](http://docs.python.org/2/library/profile.html) – Wrikken Mar 09 '13 at 01:00
4 Answers
at shell, you can run cProfile module as a script:
python -m cProfile nameofscriptfile.py

- 1,572
- 2
- 16
- 29
Python code is not executed as is, the program you typed in is compiled into an intermediate format that is optimized. So the same line can very well take different times depending on the surrounding lines. Also, Python has complex operations on its data, the time an operation takes will depend on the exact values handled.

- 11,412
- 8
- 32
- 52
Here's a quick and dirty way.
Step 1. Run it and get end-to-end overall time in seconds. If it's really quick, wrap a temporary outer loop around it, to make it take at least a few seconds.
Step 2. Get a bunch of random-time stack samples, as in this example. You can do this over multiple runs if the run-time is short.
Any line you are interested in appears on some fraction of the samples. If, for example, it appears on 3 out of 10 samples, that means during 30% (roughly) of the overall time, that statement was executing.

- 1
- 1

- 40,059
- 14
- 91
- 135