Profiling: check how long it takes to run a Python script

flaviabastos

Flávia Bastos

Posted on December 7, 2018

Profiling: check how long it takes to run a Python script

From Python’s official documentation: “A profile is a set of statistics that describes how often and for how long various parts of the program executed.”

Python’s standard library provides two implementations of the same profiling interface: cProfile and profile but I always go with cProfile for short scripts because you can invoke it at run time like so (no import required!):

python3 -m cProfile foo.py

The output provides you the total runtime and also a break down by call type, which can be very helpful when you are looking for ways to optimize a script.

cProfile example output:

         131 function calls in 0.001 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.001 0.001 loops.py:4(<module>) 1 0.000 0.000 0.001 0.001 loops.py:4(multiple\_loops) 1 0.000 0.000 0.001 0.001 {built-in method builtins.exec} 58 0.001 0.000 0.001 0.000 {built-in method builtins.print} 1 0.000 0.000 0.000 0.000 {method 'disable' of '\_lsprof.Profiler' objects} 40 0.000 0.000 0.000 0.000 {method 'insert' of 'list' objects} 29 0.000 0.000 0.000 0.000 {method 'join' of 'str' objects}

The post Profiling: check how long it takes to run a Python script was originally published at flaviabastos.ca

💖 💪 🙅 🚩
flaviabastos
Flávia Bastos

Posted on December 7, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related