Sektion 3. Kapitel 5
single
Challenge: Profiling and Fixing a Leaky Pipeline
Stryg for at vise menuen
Opgave
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]
- 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øsning
Var alt klart?
Tak for dine kommentarer!
Sektion 3. Kapitel 5
single
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat