Python

Python Performance Profiling: Finding and Fixing Slow Code

A Python application can work perfectly and still perform poorly. An API endpoint might take several seconds to respond, a background job might process data…

D
DevByteTechnical Author
Published
15 min read1 views
Python Performance Profiling: Finding and Fixing Slow Code

A Python application can work perfectly and still perform poorly. An API endpoint might take several seconds to respond, a background job might process data too slowly, or a script might consume excessive CPU and memory as the dataset grows.

The natural reaction is to start optimizing loops, replacing functions, or rewriting code. However, optimizing without understanding where the time goes often leads to unnecessary complexity without meaningful performance improvements.

This is where Python performance profiling becomes essential.

Profiling helps developers identify which functions consume the most execution time, where applications spend their resources, and which operations deserve optimization. Instead of guessing, you can use profiling tools to measure performance and make data-driven decisions.

In this guide, we'll explore Python's built-in profiling tools, measure execution time, identify slow functions, investigate memory consumption, and optimize a practical application using real examples.

1. What Is Python Performance Profiling?

Performance profiling is the process of measuring an application's behavior while it executes.

A profiler collects information about execution time, function calls, memory allocation, or resource utilization. You can use this information to identify bottlenecks and understand how your application behaves under different workloads.

Consider a Python API that processes customer orders. Its response time might be affected by several operations:

  • Fetching records from a database.

  • Calling an external API.

  • Performing calculations.

  • Processing large collections.

  • Serializing results into JSON.

Without profiling, you might assume that a complex calculation is responsible for the delay. In reality, the application could be spending most of its time waiting for the database.

Profiling helps distinguish between these possibilities.

Types of performance profiling

Profiling Type

What It Measures

Common Tools

Deterministic profiling

Function calls and execution time

cProfile, profile

Line-level profiling

Time spent executing individual lines

line_profiler

Memory profiling

Memory usage and allocation patterns

tracemalloc, Memray

Sampling profiling

Periodic snapshots of executing code

py-spy, Scalene

Benchmarking

Execution time for specific operations

timeit, pytest-benchmark

Different tools answer different questions. You don't need to use all of them for every performance problem.

2. Measure Execution Time Before Optimizing

The first step is to establish a baseline.

A baseline tells you how long your code takes to execute before you make changes. You can compare the results after optimization to determine whether your changes actually improved performance.

Using Python's time module

For a simple measurement, use time.perf_counter().

import time


def process_orders():
    total = 0

    for order_id in range(1_000_000):
        total += order_id

    return total


start = time.perf_counter()

result = process_orders()

end = time.perf_counter()

print(f"Result: {result}")
print(f"Execution time: {end - start:.4f} seconds")

time.perf_counter() provides a high-resolution performance counter suitable for measuring elapsed time.

This approach is useful when you want to measure a specific operation.

However, one execution isn't always representative of real performance. Operating system scheduling, CPU frequency changes, background processes, and caching can affect measurements.

Measure multiple executions

For more reliable measurements, repeat the operation:

import statistics
import time


def calculate_total():
    return sum(range(1_000_000))


execution_times = []

for _ in range(7):
    start = time.perf_counter()

    calculate_total()

    elapsed = time.perf_counter() - start
    execution_times.append(elapsed)

print("Minimum:", min(execution_times))
print("Median:", statistics.median(execution_times))
print("Maximum:", max(execution_times))

The median can be more representative than a single measurement because it is less sensitive to unusually slow runs.

For serious benchmarking, consider warm-up effects, realistic input sizes, stable test environments, and tools such as pyperf.

Important: Don't include unrelated work in your measurements. For example, if you're benchmarking a calculation, avoid including file downloads, database setup, or application startup unless those operations are part of what you intend to measure.

3. Finding Slow Functions with cProfile

Python includes a deterministic profiler called cProfile.

It collects statistics about function calls, including the number of calls and the time spent executing functions.

Suppose you have the following application code:

def calculate_squares(numbers):
    return [number ** 2 for number in numbers]


def calculate_cubes(numbers):
    return [number ** 3 for number in numbers]


def process_data():
    numbers = list(range(1, 500_000))

    squares = calculate_squares(numbers)
    cubes = calculate_cubes(numbers)

    return squares, cubes


process_data()

You can profile the program directly from the command line.

Save the code in app.py, then execute:

python -m cProfile -s cumulative app.py

The -s cumulative option sorts the output by cumulative time.

This helps identify functions that consume substantial time, including time spent in functions they call.

Understanding cProfile output

The output includes columns such as:

Column

Meaning

ncalls

Number of calls to a function

tottime

Time spent inside the function itself, excluding subcalls

percall

Time per call for the corresponding timing measurement

cumtime

Time spent in the function and its subcalls

filename:lineno(function)

Location and name of the function

Two measurements deserve particular attention.

Total time (tottime) is useful for identifying functions that perform expensive work directly.

Cumulative time (cumtime) is useful for identifying functions that consume substantial time across their entire call hierarchy.

For example, an API handler might have a low total time but a high cumulative time because it calls a slow database function.

Save profiling results for later analysis

For larger applications, save the profiling statistics to a file:

python -m cProfile -o profile_results.prof app.py

You can then inspect the saved profile using Python:

import pstats


stats = pstats.Stats("profile_results.prof")

stats.strip_dirs()
stats.sort_stats("cumulative")
stats.print_stats(20)

This displays the 20 entries at the top of the selected sort order.

You can also sort by internal execution time:

stats.sort_stats("tottime")
stats.print_stats(20)

This is useful when you want to identify functions performing expensive work directly rather than functions whose cost primarily comes from their dependencies.

When should you use cProfile?

Use cProfile when:

  • A Python script takes too long to complete.

  • You suspect a particular workflow has become slower.

  • You want to understand which functions dominate execution time.

  • You need profiling data that you can save and compare.

One limitation is that profiling adds overhead. Treat the results as diagnostic information rather than a perfect representation of uninstrumented production latency.

4. A Real Optimization Example: Removing Repeated Searches

Let's examine a common performance problem.

Imagine that you receive a list of orders and a separate list of customers. You need to attach the corresponding customer name to every order.

A straightforward implementation might look like this:

def attach_customer_names(orders, customers):
    result = []

    for order in orders:
        customer_name = None

        for customer in customers:
            if customer["id"] == order["customer_id"]:
                customer_name = customer["name"]
                break

        result.append({
            **order,
            "customer_name": customer_name,
        })

    return result

This implementation searches the customer list for every order.

If there are 10,000 orders and 10,000 customers, the worst-case number of comparisons can approach 100 million.

As the input grows, the repeated searches become expensive.

Optimize using a dictionary

You can index customers by ID before processing the orders.

def attach_customer_names_optimized(orders, customers):
    customers_by_id = {
        customer["id"]: customer["name"]
        for customer in customers
    }

    result = []

    for order in orders:
        result.append({
            **order,
            "customer_name": customers_by_id.get(
                order["customer_id"]
            ),
        })

    return result

The dictionary provides average-case constant-time lookups, making the overall algorithm approximately linear in the number of orders and customers.

Let:

  • O represent the number of orders.

  • C represent the number of customers.

The original implementation has worst-case time complexity of O × C, or O(OC).

The optimized implementation has expected time complexity of O(O + C), assuming typical dictionary performance.

Benchmark both implementations

import time


customers = [
    {"id": customer_id, "name": f"Customer {customer_id}"}
    for customer_id in range(10_000)
]

orders = [
    {
        "id": order_id,
        "customer_id": order_id % 10_000,
    }
    for order_id in range(10_000)
]


start = time.perf_counter()
attach_customer_names(orders, customers)
original_time = time.perf_counter() - start

start = time.perf_counter()
attach_customer_names_optimized(orders, customers)
optimized_time = time.perf_counter() - start

print(f"Original: {original_time:.4f}s")
print(f"Optimized: {optimized_time:.4f}s")

The exact timings depend on your hardware, Python version, and workload.

The important improvement comes from changing the algorithm rather than simply changing the syntax.

Practical lesson: Before trying micro-optimizations, examine whether your code is performing unnecessary repeated work.

5. Profiling Individual Lines with line_profiler

Sometimes, cProfile identifies a slow function, but you still need to determine which line inside that function causes the problem.

For this situation, you can use line_profiler.

Install it with:

pip install line_profiler

Consider this function:

def process_records(records):
    results = []

    for record in records:
        normalized = record["name"].strip().lower()

        score = 0

        for value in record["values"]:
            score += value * value

        results.append({
            "name": normalized,
            "score": score,
        })

    return results

You might suspect that string normalization, the inner loop, or dictionary creation is responsible for the delay.

Line-level profiling can help determine which operation consumes the most time.

Recent versions of line_profiler support the LINE_PROFILE environment variable for selecting functions to profile.

For example, with a compatible version:

LINE_PROFILE=process_records kernprof -l -v app.py

The exact setup can vary with the installed version and execution environment. Consult the tool's documentation for the recommended invocation for your version.

The resulting report provides timing statistics for individual lines in the selected function.

When is line-level profiling useful?

Use it when:

  • You have already identified a slow function.

  • Several operations inside that function could be responsible.

  • You need to compare the relative cost of individual lines.

  • You want to understand whether a loop, transformation, or allocation is expensive.

Avoid profiling every line of every function by default. Start with the slowest functions and investigate only where necessary.

6. Finding Memory Problems with tracemalloc

An application can become slow because it uses too much memory.

For example, a data-processing script might load millions of records into memory, create multiple copies of the same dataset, or accumulate cached objects without releasing them.

Python's built-in tracemalloc module helps trace memory allocations made by Python's memory allocator.

Here's a practical example:

import tracemalloc


tracemalloc.start()

records = [
    {
        "id": record_id,
        "name": f"Record {record_id}",
        "values": list(range(100)),
    }
    for record_id in range(10_000)
]

current, peak = tracemalloc.get_traced_memory()

print(f"Current traced memory: {current / 1024 / 1024:.2f} MB")
print(f"Peak traced memory: {peak / 1024 / 1024:.2f} MB")

tracemalloc.stop()

This reports the current and peak traced memory since tracing started.

Note that traced memory is not the same as total process memory. Native extensions and other allocations may not be fully represented.

Find where allocations occur

You can compare snapshots to identify code locations responsible for increased traced memory:

import tracemalloc


tracemalloc.start()

before = tracemalloc.take_snapshot()

records = [
    {"id": item, "values": list(range(100))}
    for item in range(10_000)
]

after = tracemalloc.take_snapshot()

differences = after.compare_to(before, "lineno")

for stat in differences[:10]:
    print(stat)

tracemalloc.stop()

The comparison highlights differences between the snapshots, grouped by source line.

This is useful for investigating unexpectedly large allocations.

Common memory optimization techniques

Depending on what profiling reveals, you might:

  • Process large files in batches.

  • Use generators instead of constructing entire intermediate lists.

  • Avoid repeatedly copying large dictionaries or lists.

  • Limit cache size and expiration.

  • Release references to objects that are no longer needed.

  • Use appropriate data structures for the workload.

For example, instead of loading an entire file into memory:

with open("large_file.txt", encoding="utf-8") as file:
    lines = file.readlines()

You can process it line by line:

with open("large_file.txt", encoding="utf-8") as file:
    for line in file:
        process_line(line)

The second approach avoids creating a list containing every line at once.

However, generators are not automatically faster. Their main advantage in this example is reducing the need to store all lines simultaneously.

7. Profiling Slow Python Applications in Production

Profiling a small script is relatively straightforward. Profiling a production application requires additional care because real workloads include concurrent requests, database operations, external services, and background tasks.

For production debugging, sampling profilers can be useful.

One popular option is py-spy.

Install it using:

pip install py-spy

You can inspect a running Python process:

py-spy top --pid 12345

Replace 12345 with the actual process ID.

To record a profiling session:

py-spy record -o profile.svg --pid 12345

This produces a flame graph that visualizes where the process spends its time.

A flame graph can help you identify:

  • Functions consuming substantial CPU time.

  • Deep call stacks.

  • Repeated expensive operations.

  • Hot paths inside frameworks and libraries.

Sampling profilers periodically inspect the executing process instead of instrumenting every function call. This often makes them useful for investigating running services.

Before attaching any profiler to production, verify the tool's permissions, operational impact, security requirements, and compatibility with your environment.

CPU time versus waiting time

A crucial distinction is whether your application is actively computing or waiting.

For example, a request might spend:

  • 20 milliseconds calculating a response.

  • 400 milliseconds waiting for a database query.

  • 300 milliseconds waiting for an external API.

A CPU profiler may not fully explain the time spent waiting for external operations.

For web applications, combine profiling with request tracing, database query timing, HTTP client metrics, and application logs.

This helps you distinguish CPU bottlenecks from network latency and other I/O delays.

8. Optimizing Slow FastAPI Endpoints

Python profiling becomes especially valuable when an API endpoint has unexpectedly high latency.

Consider a FastAPI endpoint:

from fastapi import FastAPI
import time

app = FastAPI()


@app.get("/report")
def generate_report():
    time.sleep(1)

    result = sum(range(1_000_000))

    return {
        "result": result,
    }

This example deliberately combines a one-second wait with a calculation.

If you profile it, you may discover that the endpoint's delay comes primarily from waiting rather than CPU-intensive work.

The time.sleep() call is only illustrative; real applications typically wait for database queries, network requests, or other I/O operations.

Step 1: Measure endpoint latency

Send multiple requests and record response times using an HTTP benchmarking tool or your application's existing observability system.

Measure both typical and high-percentile latency, such as p50 and p95.

A single request might not reveal intermittent delays or the impact of concurrency.

Step 2: Inspect database queries

Look for:

  • Queries that scan too many records.

  • Missing indexes.

  • N+1 query patterns.

  • Repeated database requests for the same data.

  • Excessive result sizes.

If a database query dominates request time, optimizing Python loops may have little effect.

Step 3: Investigate external API calls

Measure the time spent waiting for external services.

Depending on the use case, you might benefit from connection pooling, caching, bounded concurrency, or timeouts.

Step 4: Check synchronous and asynchronous operations

FastAPI supports both def and async def endpoints.

An asynchronous endpoint can improve concurrency when it uses non-blocking I/O operations correctly. However, placing blocking operations inside an async def function can prevent the event loop from serving other tasks efficiently.

For example, avoid using time.sleep() inside an asynchronous endpoint. Use await asyncio.sleep() for an asynchronous delay, or use the appropriate asynchronous client for real I/O operations.

Also remember that asynchronous programming does not automatically make CPU-intensive calculations faster. CPU-bound workloads may require algorithmic optimization, process-based parallelism, or specialized libraries.

Step 5: Profile again

After changing the code, repeat the same measurements under comparable conditions.

Confirm that the change improved the behavior you intended to improve and did not introduce regressions elsewhere.

9. Using timeit for Small Performance Comparisons

Sometimes you don't need a full profiler. You simply want to compare two implementations of a small operation.

Python's timeit module is designed for this purpose.

Suppose you want to compare list comprehensions with an explicit loop.

import timeit


comprehension_time = timeit.timeit(
    "[x * x for x in range(1000)]",
    number=10_000,
)

loop_time = timeit.timeit(
    """
result = []
for x in range(1000):
    result.append(x * x)
""",
    number=10_000,
)

print(f"List comprehension: {comprehension_time:.4f}s")
print(f"For loop: {loop_time:.4f}s")

The exact results depend on your Python version and environment.

timeit is useful for small, isolated benchmarks, but it does not explain why an entire application is slow.

For more sophisticated benchmarking, consider pyperf, which provides tools to improve the reliability and reproducibility of Python benchmarks.

Avoid misleading benchmarks

When comparing implementations:

  1. Use identical input data.

  2. Run enough iterations to reduce noise.

  3. Avoid comparing results from heavily loaded and idle systems.

  4. Measure memory usage if allocation behavior matters.

  5. Benchmark realistic input sizes.

  6. Verify that both implementations produce equivalent results.

A function that performs better on 100 records might behave differently on 10 million records.

10. Common Python Performance Mistakes

Optimizing before measuring

Developers sometimes rewrite code based on intuition.

Better approach: Establish a baseline, identify the bottleneck, and optimize the operation responsible for the measured cost.

Ignoring algorithmic complexity

A nested search might work well for small datasets but become extremely slow as the dataset grows.

Better approach: Evaluate whether dictionaries, sets, indexes, batching, or a different algorithm can eliminate unnecessary work.

Using caching without limits

Caching repeated computations can improve performance, but an unbounded cache may consume excessive memory.

Better approach: Use an appropriate cache size, expiration policy, and invalidation strategy.

Assuming async solves every performance problem

Asynchronous programming can improve I/O concurrency, but it doesn't automatically accelerate CPU-intensive calculations.

Better approach: Determine whether the bottleneck is CPU, I/O, memory, or database-related before selecting an optimization technique.

Ignoring database performance

Slow queries can make a Python application appear inefficient even when the application code is relatively fast.

Better approach: Measure query execution time, inspect query plans, and investigate indexes and query patterns.

Trusting a single benchmark

One measurement can be distorted by system activity, initialization costs, and caching.

Better approach: Repeat measurements and compare results under consistent conditions.

Optimizing code that doesn't matter

A small helper function might be inefficient but account for only a tiny fraction of total execution time.

Better approach: Prioritize bottlenecks based on their contribution to the application's overall cost.

11. A Practical Performance Optimization Workflow

For real-world Python projects, a repeatable workflow is more useful than memorizing individual profiling tools.

Step 1: Define the problem

Identify what is slow.

Examples include API response time, background job duration, memory usage, or CPU utilization.

Step 2: Establish a baseline

Record performance before changing the implementation.

For APIs, collect latency percentiles and request throughput. For batch jobs, record processing time and memory consumption.

Step 3: Profile the application

Choose a suitable tool:

  • cProfile for function-level execution statistics.

  • line_profiler for individual line timings.

  • tracemalloc for traced Python memory allocations.

  • py-spy for sampling a running Python process.

  • timeit for small, isolated benchmarks.

Step 4: Identify the dominant bottleneck

Determine whether the problem is caused by computation, repeated work, memory allocation, database queries, or waiting for external services.

Step 5: Make one meaningful change

Examples include replacing repeated searches with a dictionary, reducing unnecessary allocations, improving a query, or introducing appropriate caching.

Step 6: Run tests

Ensure the optimization preserves the expected behavior.

Performance improvements are not worthwhile if they introduce incorrect results or security problems.

Step 7: Benchmark again

Repeat the original measurements using comparable input and environmental conditions.

Calculate the speedup as:

Speedup = Original execution time ÷ Optimized execution time

For example, if an operation decreases from 4 seconds to 1 second:

Speedup = 4 ÷ 1 = 4×

The execution time has decreased by 75%.

Step 8: Monitor production behavior

Confirm that the improvement persists under realistic workloads.

Watch for regressions in latency, memory usage, error rates, and resource consumption.

Conclusion

Python performance profiling helps developers understand why applications are slow and where optimization efforts will have the greatest impact.

Start with simple timing measurements, use cProfile to identify expensive functions, and investigate individual lines or memory allocations when necessary. For running services, sampling profilers and application observability tools can reveal bottlenecks that are difficult to reproduce locally.

Most importantly, optimize based on evidence rather than assumptions. Improving algorithmic complexity, eliminating repeated work, optimizing database queries, and managing memory effectively often produce more meaningful gains than making small syntax changes.

A reliable optimization process follows a simple principle: measure, profile, optimize, test, and measure again.

Further Reading

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘