cProfile
module is a built-in profiler that allows you to measure the performance of your code by recording the number of function calls and the time spent in each function. The ncalls
attribute in the profiling results indicates the number of times a particular function was called during the profiling run. Here’s how you can use cProfile
and access the ncalls
information:
- Import the
cProfile
module:
import cProfile
Code language: Python (python)
- Decorate the function you want to profile with
cProfile.run()
:
Decorate the function you want to profile with cProfile.run():
Code language: Python (python)
In the example above, replace my_function
with the name of the function you want to profile.
- Run your Python script. This will execute the
my_function
while profiling it withcProfile
. - After running your script, you will get profiling results printed to the console. These results include information about the number of calls to each function. The
ncalls
column in the profiling results shows the number of times each function was called.
Here’s a simplified example of what the profiling results might look like:
1000002 function calls in 2.123 seconds
Ordered by: cumulative time
ncalls tottime percall cumtime percall filename:lineno(function)
1000000 0.456 0.000 1.234 0.000 my_module.py:10(my_function)
...
Code language: Python (python)
In this example, ncalls
shows that my_function
was called 1,000,000 times during the profiling run.
You can use this information to identify which functions are consuming the most time and optimize your code accordingly.
Read More;
- Python cProfiler Decorator [With Example]
- Python cProfile Multiprocessing With Example
- CProfileV: Making Python cProfile Usage Effortless
- Python cProfile Vs Timeit
- Python cProfile tottime vs cumtime
- Python cProfile With Arguments [With Example]
- Profile a Jupyter Notebook in Python
- Python cProfile Not Working [Solutions]
- Python cProfile Name is Not Defined (Fixed)
- Managing cProfile Output Files for Python Profiling
- Python cProfile Command Line
- Python cProfile Sort