Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Challenge: Profiling and Fixing a Leaky Pipeline | Profiling and Leak Detection
Python Memory Management
Section 3. Chapter 5
single

single

Challenge: Profiling and Fixing a Leaky Pipeline

Swipe to show menu

Task

Swipe to start coding

You are given a data processing script that has a memory problem. Your task is to use tracemalloc to measure allocations before and after an operation, then fix the leak using the tools covered in this section.

You are given the following leaky function:

report_cache = {}

def generate_report(report_id):
    if report_id not in report_cache:
        report_cache[report_id] = list(range(500))
    return report_cache[report_id]
  1. Import tracemalloc and functools.
  2. Start tracing with tracemalloc.start() and take a snapshot called snapshot_before.
  3. Call generate_report(report_id) for report_id in range(2000) in a loop.
  4. Take a second snapshot called snapshot_after and stop tracing with tracemalloc.stop().
  5. Compare the snapshots using compare_to("lineno") and store the result in top_stats. Print the first element of top_stats.
  6. Define a new function generate_report_fixed(report_id) decorated with @functools.lru_cache(maxsize=256) that returns list(range(500)).

Solution

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 5
single

single

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt