python profiler
Python hosting: Host, run, and code Python in the cloud!
In this article you will learn how to profile a python program.
Profiling is a form of program analysis. It can help us answer questions such as:
- how much memory is the program using?
- how much time is spent on functions?
- how much time is spent on statements?
Related Course:
Python Programming Bootcamp: Go from zero to hero
python profiling
cProfile is a profiler included with Python. The profiler gives the total running time, tells the function call frequency and much more data.
Take any program to measure, for example this simple program:
|
Instead of executing it the traditional way, run python like this:
|
You will see something like this:
|
To visualize the profiling data we can use these steps:
|
A lot of time is spent in the factorial function, the sinus function hardly takes any time (the sinus function running time is the small block on the right). We can iterate over each function and show the running time as percentage.
visualize your code flow graph
The module pycallgraph can visualize your code run time.
Install it using:
|
The software graphviz is required, you can get it from https://graphviz.org/ or use the command:
|
After installing, run:
|
and image called pycallgraph.png will be created. You can load it in a file explorer or type:
|
It will output a call graph with run times:
python memory profiler
To visualize run time and memory usage, we can also use vprof.
Install with:
|
To show the memory use (a browser will open):
|
It shows a memory plot, with total memory use, lines of code and so on:
To show the number of executions for each line of code:
|
The window highlights each line of code with the number of calls, the more calls the darker the lines:
You can get a flame graph with the line:
|
And combine all graphs using:
|
Leave a Reply: