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

single

Challenge: Profiling and Fixing a Leaky Pipeline

Swipe um das Menü anzuzeigen

Aufgabe

Wischen, um mit dem Codieren zu beginnen

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

Lösung

Switch to desktopWechseln Sie zum Desktop, um in der realen Welt zu übenFahren Sie dort fort, wo Sie sind, indem Sie eine der folgenden Optionen verwenden
War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 3. Kapitel 5
single

single

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

some-alt