Python comes with a powerful profiling tool — cProfile that lets you look at the time spent on every method that your code hits — user defined as well as built-in methods.

It is simple to use and the statistics could be used to see which parts of the code are taking longer to run and optimize them.


A program that prints the fibonacci sequence:

Using the cProfile:

So, to run the profiler, we will first need to import cProfile and enable it :

Then, we call the method to print the fibonacci sequence :

Once it’s done, we disable the profile and print the statistics:

This is how the script looks:


We can see that most of the time that the script spends is in the method time.sleep() — 5 seconds in total and 1.001 seconds per call.

Notice the number of calls of the recursive function fib — 33/5. It has been called 33 times overall but 5 times on separate occasions.