From stack samples to a trace
Anthropic software engineer candidates report a coding question about profiler samples (3 reports). A staff candidate was asked to find the slowest part of the code from samples like these (1 report). It starts like this:
A sampling profiler stops a program every so often and records its call stack. One sample is
(time, stack), wherestacklists function names, outermost call first, as a Python traceback does.Write
trace(samples). Return the events(time, kind, name), wherekindis"start"or"end", for every function call the samples show. A call that's gone in the next sample ended at that sample's time, and the last sample ends every call still open.
Sample Events (0, ["main"])(0, "start", "main")(10, ["main", "load"])(10, "start", "load")(20, ["main", "parse"])(20, "end", "load"),(20, "start", "parse")(30, [])(30, "end", "parse"),(30, "end", "main")
Then the interviewer asks for time: how long each function ran, and which one is slowest. After that come the cases real programs bring, such as a function that calls itself.
You don't write it yet. Working out which calls kept running between two samples is a stack question, so the first parts teach the stack itself, with the stack problems interviewers also ask, and part 4 turns to the samples. At the end you solve the whole problem, level by level, in an interview simulation with a 45-minute timer.
A stack is the order in which a program's calls open and close, and that order is exactly what profiler samples record. The idea of last in, first out comes back in the topological sort lesson, where depth-first search keeps the same kind of stack.