How to Profile Python Code with cProfile and pstats

Data-processing pipeline with a highlighted bottleneck for Python performance profiling

What You’ll Learn

In this lesson, you will use Python’s built-in cProfile profiler and the pstats module to find slow functions in a data-processing application before changing its implementation.

  • Run a profiler around a specific section of Python code.
  • Read cumulative time, total time, and call-count information.
  • Sort profiling results with pstats.
  • Decide which function is the best optimization target.
  • Save profiling data for later inspection.
Ad

The Concept

Profiling measures how a program spends its execution time. Instead of guessing which function is slow, you can collect timing and call-count data while the program runs.

cProfile is Python’s built-in deterministic profiler. It records information about function calls, including:

  • Number of calls: how often a function runs.
  • Total time: time spent inside the function itself, excluding functions it calls.
  • Cumulative time: time spent in the function and all functions called from it.

The pstats module reads and formats these results. Sorting by cumulative time is often a useful first step because it reveals functions responsible for the largest overall portions of a workflow. Sorting by total time can help identify code that performs expensive work directly.

Profiling is most useful after you have a representative workload. A tiny test dataset may not expose the same bottleneck as a production-sized dataset. Also, profiling adds overhead, so use it to guide development and investigation rather than as a precise measurement of production latency.

Basic Example

This example processes customer records from a data-processing pipeline. It normalizes text, counts important terms, and calculates a simple priority score. The profiler is placed around the workload rather than around the whole program, so the report focuses on the functions we want to investigate.

If your processing code uses parallel iteration over related lists or records, Python’s enumerate() and zip() functions can provide useful groundwork for organizing that data-processing logic.

import cProfile
import pstats


KEYWORDS = ("refund", "delay", "cancel")


def normalize_message(message):
    return " ".join(message.lower().split())


def score_record(record):
    message = normalize_message(record["message"])
    keyword_count = sum(message.count(keyword) for keyword in KEYWORDS)
    return {
        "customer": record["customer"],
        "score": keyword_count + record["amount"] // 100,
    }


def process_records(records):
    return [score_record(record) for record in records]


def main():
    records = [
        {
            "customer": "Amina",
            "amount": 240,
            "message": "Refund requested after delivery delay",
        },
        {
            "customer": "Jon",
            "amount": 80,
            "message": "Customer wants to cancel the order",
        },
        {
            "customer": "Mei",
            "amount": 510,
            "message": "Delivery delay reported twice",
        },
        {
            "customer": "Luis",
            "amount": 120,
            "message": "Question about a completed order",
        },
    ]

    profiler = cProfile.Profile()
    profiler.enable()
    scored_records = process_records(records)
    profiler.disable()

    print(f"Processed {len(scored_records)} records")

    stats = pstats.Stats(profiler)
    stats.strip_dirs().sort_stats("cumulative").print_stats(8)


if __name__ == "__main__":
    main()

Expected Output

The first line is stable. The timing values and exact list of functions can vary by Python version and computer speed. The profiler then prints a table containing fields such as ncalls, tottime, cumtime, and the source location of each function.

Processed 4 records
         20 function calls in 0.000 seconds

   Ordered by: cumulative time
   List reduced from ... to 8 due to restriction <8>

Very small workloads may show 0.000 seconds because the measured operations complete faster than the display precision. In a real application, profile a larger representative input to produce more useful timing differences.

How the Code Works

A process diagram showing a representative data-processing workload wrapped by cProfile, followed by pstats sorting and inspection of timing and call-count data, a decision about the optimization target, and either profiling data being saved for later analysis or the selected function being optimized and reprofiled.
Profile a representative workload, inspect cumulative and total time with pstats, then optimize the function supported by the evidence and compare another run.

cProfile.Profile() creates a profiler object that can be controlled directly. Calling enable() starts recording, and disable() stops recording after process_records() finishes.

The code does not profile the setup of the sample records or the final report. This keeps the report focused on the data-processing workload:

profiler = cProfile.Profile()
profiler.enable()
scored_records = process_records(records)
profiler.disable()

pstats.Stats(profiler) turns the collected data into a statistics object. strip_dirs() makes file paths shorter, while sort_stats("cumulative") places functions with the greatest cumulative time first. Finally, print_stats(8) limits the display to the first eight entries.

When you inspect the table, distinguish between tottime and cumtime. If a high cumulative time belongs to process_records(), that may simply mean it calls other functions many times. A lower-level function with high total time may be doing the expensive work directly and could be the better optimization target.

For this small example, the report is mainly demonstrating the workflow. With thousands of records, you might discover that repeated string scanning in score_record(), file parsing, database calls, or another function dominates the report. Optimize the function supported by the profile rather than assuming its name alone identifies the problem.

Another Example

You can also save profiling results to a file. This is useful when the data-processing job takes a long time, when you want to compare runs, or when someone else needs to inspect the results later.

The following script reads comma-separated transaction data from a file, aggregates totals by region, and saves the profile as transaction_profile.prof.

import cProfile
import csv
import pstats
import sys
from collections import defaultdict


def summarize_transactions(path):
    totals_by_region = defaultdict(float)

    with open(path, newline="", encoding="utf-8") as transaction_file:
        for row in csv.DictReader(transaction_file):
            region = row["region"]
            amount = float(row["amount"])
            totals_by_region[region] += amount

    return dict(totals_by_region)


def main():
    if len(sys.argv) != 2:
        raise SystemExit("Usage: python transaction_summary.py transactions.csv")

    profiler = cProfile.Profile()
    profiler.enable()
    summary = summarize_transactions(sys.argv[1])
    profiler.disable()

    print(summary)

    stats = pstats.Stats(profiler)
    stats.dump_stats("transaction_profile.prof")
    stats.strip_dirs().sort_stats("cumulative").print_stats(10)


if __name__ == "__main__":
    main()

Run the script with a real input file:

python transaction_summary.py transactions.csv

The call to dump_stats() writes the collected data in a format that tools and pstats can read later. You can inspect the saved file interactively with Python’s built-in statistics browser:

python -m pstats transaction_profile.prof

Inside the pstats prompt, commands such as sort cumulative and stats 10 let you sort the report and display the top ten entries. The exact timing report depends on the size and contents of transactions.csv.

Common Mistakes

Profiling the wrong section

If you enable profiling before loading configuration, creating test data, and printing reports, those operations can distract from the workload you are trying to understand. Start profiling immediately before the function or pipeline stage under investigation.

Optimizing the function with the largest call count

A function called thousands of times is not automatically the bottleneck. Each call may be very cheap. Compare call counts with total and cumulative time before choosing an optimization target.

Confusing cumulative time with self time

A wrapper function can have high cumulative time because it calls expensive helpers. Look at both cumulative time and total time to determine whether the cost is inside the function itself or inside its callees.

Profiling an unrealistic dataset

With only four records, timing differences are often too small to interpret. Use a dataset that resembles the size, distribution, and processing steps of the real application. Repeat the same workload when comparing before and after versions.

Assuming profiling proves correctness

A profiler measures performance; it does not verify that the result is correct. Keep tests and data-validation checks in place while changing the implementation.

Try It Yourself

Modify the first example so that it processes at least 1,000 records. You can create the larger input by repeating the sample records, then profile the workload again.

Sort the results by both of these keys in separate runs:

  • "cumulative", to find functions responsible for the most overall processing time.
  • "time", to find functions spending the most time in their own code.

Compare the two reports. Which function appears near the top in each report, and what does that suggest about where its work occurs?

Challenge

Create a profiling script for a shipment-processing workload.

  • Define a function named calculate_shipping_total(shipments).
  • Each shipment should contain a "zone" and a "weight".
  • Use a rate table to calculate a total cost for each zone.
  • Return a dictionary containing the total cost per zone.
  • Profile the function with cProfile.
  • Print the totals and the ten functions with the greatest cumulative time.
  • Save the profile data to shipping_profile.prof.

Use enough shipments to make the workload meaningful, and choose an optimization target only after examining the report.

Solution

import cProfile
import pstats


ZONE_RATES = {
    "local": 4.50,
    "regional": 7.25,
    "national": 11.00,
}


def calculate_shipping_total(shipments):
    totals_by_zone = {}

    for shipment in shipments:
        zone = shipment["zone"]
        weight = shipment["weight"]
        rate = ZONE_RATES[zone]
        shipping_cost = rate + (weight * 0.35)

        if zone not in totals_by_zone:
            totals_by_zone[zone] = 0.0

        totals_by_zone[zone] += shipping_cost

    return totals_by_zone


def main():
    zone_names = ("local", "regional", "national")
    shipments = [
        {
            "zone": zone_names[index % len(zone_names)],
            "weight": (index % 20) + 1,
        }
        for index in range(5000)
    ]

    profiler = cProfile.Profile()
    profiler.enable()
    totals = calculate_shipping_total(shipments)
    profiler.disable()

    print(totals)

    stats = pstats.Stats(profiler)
    stats.dump_stats("shipping_profile.prof")
    stats.strip_dirs().sort_stats("cumulative").print_stats(10)


if __name__ == "__main__":
    main()

The solution creates a representative shipment list, profiles only the calculation, prints the result, and stores the profile for later inspection. The report may contain different call counts or timings on different Python versions, but it will be sorted by cumulative time and limited to ten entries.

Key Takeaways

  • cProfile collects function-call and timing information without installing an external package.
  • pstats helps sort and inspect profiling results.
  • Cumulative time includes time spent in called functions, while total time measures time spent directly in the function.
  • Profile a representative workload and optimize based on measured evidence.
  • Use dump_stats() to save profiling data for later analysis or comparison.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
Ad
Ad
Ad