Python cProfile to CSV With Example

To profile a Python script using cProfile and save the profiling data to a CSV file, you can follow these steps:

  1. Import the necessary modules:
import cProfile
import pstats
import csv
Code language: Python (python)
  1. 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.

  1. 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;

    by
  • Abdullah Walied Allama

    Abdullah Walied Allama is a driven programmer who earned his Bachelor's degree in Computer Science from Alexandria University's Faculty of Computer and Data Science. He is passionate about constructing problem-solving models and excels in various technical skills, including Python, data science, data analysis, Java, SQL, HTML, CSS, and JavaScript.

Leave a Comment