Profiling Python Scripts with cProfile
Question:
Optimizing Python code can be challenging. How can you profile the execution time of a Python script to identify bottlenecks?
Answer:
Python comes equipped with a powerful profiler called cProfile. It provides a comprehensive view of execution times, including:
Using cProfile:
cProfile can be invoked in several ways:
import cProfile cProfile.run('foo()')
python -m cProfile myscript.py
python -m cProfile -m mymodule
Custom Batch File:
To simplify the process, you can create a batch file named 'profile.bat':
python -m cProfile %1
Then, simply execute your script with the file (replace euler048.py with your script):
profile euler048.py
Output:
cProfile generates a detailed output with information such as:
Additional Resources:
The above is the detailed content of How Can I Profile My Python Script to Find Performance Bottlenecks?. For more information, please follow other related articles on the PHP Chinese website!