How do you use cProfile to profile a Python script?
Profiling Python Scripts with cProfile
Using 'cProfile' to profile a Python script is straightforward. Follow these steps to profile your code and measure its performance:
Import the cProfile module:
import cProfile
Define the function or section of code to be profiled:
- Choose the function or part of code that you want to profile. You should ensure that it represents the most performance-critical part of your script.
Decorate the function (optional):
- You can use the '@cProfile.profile' decorator to profile a specific function. This step is optional, and you may use the 'cProfile.run()' function without the decorator.
Profile the function using cProfile.run():
- Use the 'cProfile.run()' function to profile the chosen function. The name of the function should be passed as a string to the run() function. Alternatively, you can use 'cProfile.runctx()' to profile an arbitrary code block. This function requires the code to be profiled as a string.
Analyze the profiling results:
- After running the script with 'cProfile', the profiling results will be displayed on the console. The output shows execution time, call count, and other statistics for each profiled function.
The following example shows how to profile Python scripts with cProfile:
Code:
#test.py
#Python Recursion: gcd of two integers
import cProfile
def Recurgcd(a, b):
low = min(a, b)
high = max(a, b)
if low == 0:
return high
elif low == 1:
return 1
else:
return Recurgcd(low, high%low)
cProfile.run('Recurgcd(12,14)')
Save the above code in a file named test.py. Then, open a terminal or command prompt and navigate to the directory containing the script. Run the script using the following command:
python script_to_profile.py
Output:
12 function calls (10 primitive calls) in 0.000 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 <string>:1(<module>) 3/1 0.000 0.000 0.000 0.000 test.py:4(Recurgcd) 1 0.000 0.000 0.000 0.000 {built-in method builtins.exec} 3 0.000 0.000 0.000 0.000 {built-in method builtins.max} 3 0.000 0.000 0.000 0.000 {built-in method builtins.min} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-interview/how-do-you-use-cprofile-to-profile-a-python-script.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics