To profile a Python script using cProfile
and save the profiling data to a CSV file, you can follow these steps:
- Import the necessary modules:
import cProfile
import pstats
import csv
Code language: Python (python)
- Profile your Python code using
cProfile
:
def your_function_to_profile():
# Your code here
if __name__ == "__main__":
profiler = cProfile.Profile()
profiler.enable()
# Call the function you want to profile
your_function_to_profile()
profiler.disable()
# Create a Stats object from the profiling data
stats = pstats.Stats(profiler)
Code language: Python (python)
Replace your_function_to_profile
with the actual function or code you want to profile.
- Save the profiling data to a CSV file:
with open("profile_data.csv", "w") as csvfile:
csv_writer = csv.writer(csvfile)
csv_writer.writerow(["ncalls", "tottime", "percall", "cumtime", "percall", "filename:lineno(function)"])
# Sort the profiling data by the desired sorting metric (e.g., 'cumulative' or 'time')
stats.sort_stats('cumulative') # You can change this to 'time' or 'calls' as needed
# Print the profiling data to the CSV file
stats.print_stats()
stats.print_stats(stream=csvfile)
Code language: Python (python)
This code will create a CSV file named “profile_data.csv” containing the profiling data for your code. You can customize the output format or the sorting metric based on your needs by modifying the sort_stats
method and the header row in the CSV file.
After running the script, you will have a CSV file with detailed profiling information that you can analyze further.
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)
- Python cProfile ncalls With Examples
- Python cProfile Limit Depth
- Python cProfile to HTML With Example