From the events, a call's total time runs from its start to its end
Push the start time with the name, and the end event pops it:
def call_durations(events):
stack, total = [], {}
for time, kind, name in events:
if kind == "start":
stack.append((name, time))
else:
name, start = stack.pop()
total[name] = total.get(name, 0) + time - start
return total
print(call_durations(EVENTS))
{'parse': 20, 'load': 30, 'save': 30, 'main': 70}
Which function is slowest? By total time it's always the outermost one, here main at 70, because its time contains everyone else's. Self time points at the code that's actually busy: save, at 30.
Adding up a recursive function's calls counts a moment more than once
A recursive function is open more than once at the same moment. Here f calls itself twice:
REC = [
(0, "start", "main"),
(0, "start", "f"),
(10, "start", "f"),
(20, "start", "f"),
(30, "end", "f"),
(30, "end", "f"),
(40, "end", "f"),
(40, "end", "main"),
]
print(call_durations(REC))
{'f': 70, 'main': 40}
That's 70 for f in a program that ran for 40. Here are the calls as bars, with how many calls of f are open in each stretch:
Calls of f open: 1 from 0 to 10, 2 from 10 to 20, 3 from 20 to 30, then 1 to 40.
Adding the calls gives 40 + 20 + 10 = 70. The stretch from 10 to 20 was counted twice, and the one from 20 to 30 three times. A function's total time should be how long at least one of its calls was open: 40.
In the editor, write most_open(events): for each function, the most of its calls open at the same moment. REC is the recursive run above.