Profiling Python Code with cProfile

Intuitive Python — by David Muller (20 / 41)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Using Python’s Built-In Database with sqli te3 | TOC | Wrapping Up 👉

Finding bottlenecks in your code can help you write more performant scripts and procedures. Python’s standard library includes a profiling module named cProfile to help you find where your program is spending its time; you’ll learn about cProfile in this section.

In general, to use cProfile you can do the following:

  1. Enable a profiler and run the code you’d like to profile (disabling the profiler when you are done).
  2. Investigate the Stats produced by the profiling session.[67]

Let’s try this out with an example. cprofile_example.py profiles the function named a and writes the Stats to a file named example.stats:

cprofile_example.py

​1: ​import​ ​cProfile​
​-
​- ​def​ ​a​():
​- b()
​5: b()
​-
​- ​def​ ​b​():
​- ​for​ i ​in​ range(250000):
​- ​pass​
​10:
​- profiler = cProfile.Profile()
​- profiler.enable()
​-
​- a()
​15:
​- profiler.disable()
​- profiler.dump_stats(​"example.stats"​)

cprofile_example.py defines two functions: a and b. All a does is call b twice, and all b does is iterate over 250,000 numbers. A profiling session is started by calling enable() on a cProfile.Profile instance bound to profiler. Then function a is called once, and the profiling session is ended by…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.