To profile Python code

Asked 1 years ago, Updated 1 years ago, 92 views

Project Euler and other coding contests often limit the program's running time or compete with each other to see how fast their code works. On Python, however, the approach of measuring the time-measuring code in _main__ was somewhat uncomfortable.

Please recommend the best way to profile the operating time of the Python program.

python performance time-complexity profiling

2022-09-22 21:16

1 Answers

Python has a built-in profiler called cProfile. This profiler measures not only the overall execution time, but also the time it takes for each function to operate, and provides information on how many times each function has been called to help determine which part needs to be optimized.

This profiler can be called in code or in interpreter :

import cProfile
cProfile.run('foo()')

Alternatively, you can call cProfile when you run a script simpler:

python -m cProfile myscript.py

To make it easier to access here, I make a small batch file called profile.bat and use it:

python -m cProfile %1

This allows you to do the same simply by running:

profile euler048.py

The result is this way:

1007 function calls in 0.061 CPU seconds

Ordered by: standard name
ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    1    0.000    0.000    0.061    0.061 <string>:1(<module>)
 1000    0.051    0.000    0.051    0.000 euler048.py:2(<lambda>)
    1    0.005    0.005    0.061    0.061 euler048.py:2(<module>)
    1    0.000    0.000    0.061    0.061 {execfile}
    1    0.002    0.002    0.053    0.053 {map}
    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}
    1    0.003    0.003    0.003    0.003 {sum}

Additionally, I share good video materials posted on PyCon 2013: http://lanyrd.com/2013/pycon/scdywg/


2022-09-22 21:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.