You can use the cProfile
module to profile the performance of your code and identify bottlenecks. To add labels to the profiling output, you can use the cProfile.run()
function with the -s
option. Here’s how you can do it:
import cProfile
def my_function():
# Your code here
if __name__ == "__main__":
label = "MyProfilingLabel" # Replace with your desired label
cProfile.run('my_function()', sort='cumulative', label=label)
Code language: Python (python)
In this example, you would replace my_function()
with the code you want to profile. The cProfile.run()
function is used to profile the my_function()
and you can specify a label using the label
parameter.
After running this script, you’ll get a profiling report that includes the specified label:
4 function calls in 0.000 seconds
Ordered by: cumulative time, descending
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 your_script.py:4(my_function)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
Code language: Python (python)
In this output, you can see the label you specified in the filename:lineno(function)
column, in this case, it would be "your_script.py:4(my_function)"
with the label you set. This can help you identify which part of your code was profiled.
Remember to replace "your_script.py:4(my_function)"
with the actual filename and line number where your function is defined in your code.
Read More;
- Python Profiling kcachegrind
- Python cProfile Filter
- Python cProfile Gunicorn With Example
- Python Profile Guided Optimization
- Profiling in FastAPI Python Applications
- Python cProfile Export With Example
- Python Error: “AttributeError: __enter__”
- subprocess-exited-with-error in Python
- Python Volume Profile With Example
- Python Profile Subprocess
- subprocess.Popen to multiprocessing
- Python Profile Plot