Python cProfile Sort: Explained With Examples

You can use the cProfile module to profile the performance of your code and analyze where it’s spending the most time. You can also sort the profiling results to focus on the functions that consume the most time.

To sort the results generated by cProfile, you can use the sort parameter when calling cProfile.run() or cProfile.Profile.run(). The sort parameter allows you to specify how the results should be sorted. There are several sorting options you can use:

  1. 'calls': Sort by the number of function calls.
  2. 'cumulative': Sort by the cumulative time spent in a function and its subfunctions.
  3. 'cumtime': Sort by the cumulative time spent in a function.
  4. 'file': Sort by the filename where the function is defined.
  5. 'module': Sort by the module where the function is defined.
  6. 'name': Sort by the function name.
  7. 'nfl': Sort by the name, filename, and line number.
  8. 'stdname': Sort by the standard name of the function.

Here’s an example of how to use cProfile and specify the sorting option:

import cProfile

def my_function():
    # Your code here

# To profile and sort by cumulative time
cProfile.run('my_function()', sort='cumulative')

# To profile and sort by number of calls
cProfile.run('my_function()', sort='calls')Code language: Python (python)

Replace 'my_function()' with the code you want to profile. After running the profiler, you will get a report sorted according to the chosen criterion, making it easier to identify performance bottlenecks in your code.

How can I sort the output of Python’s cProfile by the “percall” metric when profiling a Python script?

cProfile, you cannot directly sort the profiling results by “percall.” However, you can calculate the “percall” value yourself and then sort the results accordingly. The “percall” value represents the average time spent per function call.

Here’s how you can calculate and sort the results by “percall”:

import cProfile

def my_function():
    # Your code here

# Profile the code
profiler = cProfile.Profile()
profiler.enable()
my_function()
profiler.disable()

# Get the profiling statistics
stats = profiler.getstats()

# Calculate percall for each function and sort by it
results_sorted_by_percall = sorted(stats, key=lambda x: x[2].totaltime / x[2].ncalls)

# Print the sorted results
for func_stat in results_sorted_by_percall:
    func = func_stat[0]
    ncalls = func_stat[2].ncalls
    percall_time = func_stat[2].totaltime / ncalls
    print(f"Function: {func}")
    print(f"  Calls: {ncalls}")
    print(f"  Per Call: {percall_time:.6f} seconds")Code language: Python (python)

In this example, we calculate the “percall” time for each function by dividing the total time spent in the function by the number of calls to that function. We then sort the results based on this “percall” value.

Keep in mind that the “percall” value is just one way to analyze the performance of your code. Depending on your specific profiling goals, you might also want to consider other metrics such as cumulative time or the number of calls.

Read More;

  • 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.

    View all posts

Leave a Comment