How do I profile a Python script?
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Profiling a Python script is an essential practice when optimizing code. It helps in identifying bottlenecks, measuring code performance, and understanding memory usage. Profiling can be accomplished through different techniques and tools, and involves measuring the space (memory) and time complexity of a program.
Understanding Profiling
Profiling is the process of measuring a program's resource usage through its execution. The primary focus here is on CPU time and memory consumption, though other metrics like I/O operations can be considered. By obtaining these metrics, a developer can decide which parts of the code need optimization.
Profiling Techniques
1. cProfile
cProfile is a built-in Python module used for profiling. It provides a set of statistics detailing how long each function takes to execute and how often each function is called.
Example:
Output:
2. line_profiler
For more granular performance data, line_profiler is extremely helpful. It profiles the time consumption line-by-line within functions.
Installation:
Usage Example:
Firstly, add decorators to the functions you want to profile:
Run the Python script with:
3. memory_profiler
memory_profiler helps track the memory usage of a Python program line-by-line.
Installation:
Usage Example:
Add decorators to profile memory usage:
Execute the script, which will provide detailed memory usage:
4. Py-Spy
Py-Spy is a sampling profiler which is non-intrusive, and doesn't require code modifications. It can be used to profile running processes.
Installation:
Usage Example:
To profile a running Python process (use the PID of the process):
Or, to create a flame graph, execute:
Profiling Summary
The following table summarizes the key points for different profiling tools:
| Tool | Pros | Cons | Suitable for |
cProfile | Built-in, easy to use, comprehensive | Overheads, lacks granularity | General CPU profiling |
line_profiler | Detailed line-by-line time consumption | Needs decorators, manual setup | In-depth CPU analysis |
memory_profiler | Memory tracking, ease of use | Uses decorators, slower performance | Memory usage checks |
Py-Spy | Non-intrusive, real-time profiling | Requires external installation | Sampling, long-running programs |
Best Practices for Effective Profiling
- Identify the Problem First: Profiling should be problem-oriented. If you know the performance metric you're interested in, it’s easier to choose the correct profiling tool.
- Start with a Broad Scope and Zoom In: Use
cProfilefor a high-level insight and then drill down using more specific tools likeline_profilerormemory_profiler. - Profile in Similar Conditions: Ensure that the script runs in an environment as similar as possible to the production environment, as external factors can skew the results.
- Iterative Optimization: Profile, optimize, and then profile again. Validate that each change leads to a real improvement.
- Use Aggregated Data: In cases of sampling, use average values over multiple runs to ensure the data is reliable.
Profiling reveals where a script uses the most resources, offering clues on where to focus optimization efforts. It is a critical skill in the toolbox of performance-aware developers.
Related reading
- How do I profile a tf.data.Dataset?
- How do I profile memory usage in Python?
- How do I query between two dates using MySQL?
- How do I replace weak references when using ARC and targeting iOS 4.0?
- How do I properly assert that an exception gets raised in pytest?
- How do I properly assert that an exception gets raised in pytest?
- How do I resize the UIImage to reduce upload image size
- How do I scale one rectangle to the maximum size possible within another rectangle?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.