Abschnitt 3. Kapitel 5
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]
- Import
tracemallocandfunctools. - Start tracing with
tracemalloc.start()and take a snapshot calledsnapshot_before. - Call
generate_report(report_id)forreport_idinrange(2000)in a loop. - Take a second snapshot called
snapshot_afterand stop tracing withtracemalloc.stop(). - Compare the snapshots using
compare_to("lineno")and store the result intop_stats. Print the first element oftop_stats. - Define a new function
generate_report_fixed(report_id)decorated with@functools.lru_cache(maxsize=256)that returnslist(range(500)).
Lösung
War alles klar?
Danke für Ihr Feedback!
Abschnitt 3. Kapitel 5
single
Fragen Sie AI
Fragen Sie AI
Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen