Linux | Python Profiler
Whether you're trying to figure out why your script is crawling or you just want to optimize a specific function, Python has some built-in heavy hitters to help you find those bottlenecks.
Here is the breakdown of how to use the standard tools effectively.
1. The "Quick & Dirty" Way: cProfile
cProfile is the recommended built-in profiler for most users. It provides deterministic profiling of programs, meaning it tracks every function call, how many times it was called, and how long it took.
From the Command Line
This is the easiest way to profile a script without changing a single line of code:
1 | |
-s cumulative: Sorts the output by the cumulative time spent in each function (the most useful metric for finding bottlenecks).
Inside Your Code
If you only want to profile a specific block of code:
1 | |
2. Understanding the Output
When you run a profile, you’ll see a table with several columns. Here is what they mean:
| Column | Meaning |
|---|---|
| ncalls | Number of times the function was called. |
| tottime | Total time spent in the function (excluding time in sub-functions). |
| percall | tottime divided by ncalls. |
| cumtime | Total time spent in this and all sub-functions (from invocation to exit). |
| filename:lineno | The location of the function in your code. |
3. Visualizing the Data (Highly Recommended)
Reading text tables can get exhausting. You can export the profile data and view it as a "Flame Graph" or a call tree.
- Export to a file:
1
python -m cProfile -o output.prof my_script.py - Use a visualizer:
- SnakeViz: A web-based viewer. Install it via
pip install snakeviz, then runsnakeviz output.prof. - PyCharm: If you use the Professional edition, it has a built-in "Profile" button that generates a beautiful call graph.
- SnakeViz: A web-based viewer. Install it via
4. Deep Dive: Line-by-Line Profiling
Sometimes cProfile tells you a function is slow, but that function is 100 lines long. To see exactly which line is the culprit, use line_profiler.
- Install it:
pip install line_profiler - Decorate your function: Add
@profileabove the function you want to inspect (you don't need to import anything). - Run it:
1
kernprof -l -v my_script.py
5. Checking Memory Usage
If your script isn't slow but is crashing because it eats all your RAM, you need memory_profiler.
- Install it:
pip install memory_profiler - Decorate: Use
@profilejust like the line profiler. - Run it:
1
python -m memory_profiler my_script.py
Pro Tip: Profiling adds overhead. Your code will run slower while being profiled, so don't use these tools in a production environment unless you're using a "sampling" profiler like Py-Spy.
Example
1 | |
cProfile
$ python -m cProfile -s cumulative primes.py
1 | |
$ python -m cProfile -o output.prof primes.py$ snakeviz output.prof



memory_profiler
1 | |
Memory usage: Memory usage statusIncrement: Memory added after executing this line of code
Your code will run slower while being profiled.
1 | |