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

single

Challenge: Profiling and Fixing a Leaky Pipeline

Veeg om het menu te tonen

Taak

Veeg om te beginnen met coderen

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

Oplossing

Switch to desktopSchakel over naar desktop voor praktijkervaringGa verder vanaf waar je bent met een van de onderstaande opties
Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 3. Hoofdstuk 5
single

single

Vraag AI

expand

Vraag AI

ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

some-alt