Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (16.4k points)

Project Euler and other coding challenges frequently make some most extreme time to execute or individuals boast of how quick their specific solutions run. With Python, once in a while, the methodologies are to some degree kludgey - i.e., adding timing code to __main__

What is a decent method to profile what amount of time a Python program requires to run?

1 Answer

0 votes
by (26.4k points)

Python incorporates a profiler called cProfile. It gives the complete running time, yet in addition times each function independently, and discloses to you how often each function was called, making it simple to figure out where you should make optimizations. 

You can call it from inside your code, or from the interpreter, similar to this:

import cProfile'foo()')

While executing the script, you can also invoke cprofile

python -m cProfile

To make it considerably simpler, I made a little batch document called 'profile.bat':

python -m cProfile %1

So, only thing I have to run is:


Then I get this:

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<lambda>)

    1    0.005    0.005    0.061    0.061<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}

Are you looking for a good python tutorial? Join the python course fast and gain more knowledge in python.

Watch this video tutorial on how to become a professional in python

Related questions

Browse Categories