Generators
def squares(nums: list):
return [n * n for n in nums]
nums = list(range(500))
print(squares(nums))
import tracemalloc
from pprint import pprint
def squares(nums: list):
sqs = [n * n for n in nums]
return sqs
tracemalloc.start()
nums = list(range(500))
sqs = squares(nums)
initial_mem, peak_mem = tracemalloc.get_traced_memory()
snapshot = tracemalloc.take_snapshot()
pprint(snapshot.statistics("lineno"))
pprint(f"Peak usage: {peak_mem}")
tracemalloc.stop()
def squares(nums: list):
sqs = [n * n for n in nums]
return sqs
tracemalloc.start()
nums = list(range(500))
sqs = squares(nums)
initial_mem, peak_mem = tracemalloc.get_traced_memory()
snapshot = tracemalloc.take_snapshot()
pprint(f"Peak usage: {peak_mem}")
tracemalloc.stop()
def gen_squares(nums: list):
for n in nums:
yield n * n
tracemalloc.start()
nums = list(range(500))
squares = gen_squares(nums)
initial_mem, peak_mem = tracemalloc.get_traced_memory()
snapshot = tracemalloc.take_snapshot()
pprint(f"Peak usage: {peak_mem}")
tracemalloc.stop()
def gen_squares(nums: list):
for n in nums:
yield n * n
tracemalloc.start()
nums = list(range(500))
squares = gen_squares(nums)
square_list = [s for s in squares]
initial_mem, peak_mem = tracemalloc.get_traced_memory()
snapshot = tracemalloc.take_snapshot()
pprint(f"Peak usage: {peak_mem}")
tracemalloc.stop()
def gen_squares(nums: list):
for n in nums:
yield n * n
tracemalloc.start()
nums = range(500)
squares = gen_squares(nums)
initial_mem, peak_mem = tracemalloc.get_traced_memory()
snapshot = tracemalloc.take_snapshot()
pprint(f"Peak usage: {peak_mem}")
tracemalloc.stop()
def gen_squares(nums: list):
for n in nums:
yield n * n
tracemalloc.start()
nums = range(500)
with open("/dev/null", "w") as null:
for square in gen_squares(nums):
print(square, file=null)
initial_mem, peak_mem = tracemalloc.get_traced_memory()
snapshot = tracemalloc.take_snapshot()
pprint(f"Peak usage: {peak_mem}")
tracemalloc.stop()
Author: Breanndán Ó Nualláin <o@uva.nl>
Date: 2025-03-06 Thu 10:33