30/36
Part 8 of 8 · Follow-upsLearn and do

What about millions of samples? Hold only the previous stack

trace(samples), level 1 of the practice problem, turns all the samples into events: events_between on each neighboring pair, from an empty stack, with the last sample ending what's still open. It only needs the previous stack. So write it as a generator that yields each sample's events as it goes. It then holds two stacks at a time, O(d) memory for depth d, however many samples stream through. function_times(events, include_callees), level 2, turns the events into each function's time. It holds the open calls and one total per function, so it can read the events as they stream in too.

To see where the time goes, count identical stacks:

from collections import Counter

collapsed = Counter(";".join(stack) for _, stack in SAMPLES)
for stack, count in collapsed.items():
    print(stack, count)
main 2
main;load 1
main;load;parse 2
main;save 3

That's each distinct stack and how many samples showed it. It's the collapsed format that flame graph tools read. The docs describe it: one line per stack, function names joined by semicolons from the bottom of the stack to the top, then a space and the sample count.

events_between, the function you wrote in part 4, is at the top of the editor. Finish the generator stream(samples): it yields each sample's events and keeps only the previous stack and time.