Count only the outermost open call of each function, as cProfile's cumtime does
cProfile gives a recursive function the time at least one of its calls was open, not the sum of its calls. Here's a function that keeps the CPU busy for 10 ms and then calls itself, three calls deep:
import cProfile
import time
def spin(seconds):
end = time.perf_counter() + seconds
while time.perf_counter() < end:
pass
def walk(depth):
spin(0.01)
if depth > 1:
walk(depth - 1)
cProfile.run("walk(3)", sort="cumulative")
In its row for walk, cProfile printed 3/1 in the ncalls column and a cumtime of 0.030 s. That's the length of the outermost call alone. Adding up the three calls would give about 0.060.
The docs explain both. Two numbers in that column, like 3/1, mean the function recursed. And cumtime stays accurate even for recursive functions.
The fix is to count a call's time only when it's the outermost open call of its function. A Counter of open calls per name tells you that in O(1). It's the counting tool from the hash-maps lesson. Here it is on REC, the run where f calls itself twice:
| Event | Time | Calls of f open | Adds |
|---|---|---|---|
| start f | 0 | 1 | |
| start f | 10 | 2 | |
| start f | 20 | 3 | |
| end f | 30 | 2 | |
| end f | 30 | 1 | |
| end f | 40 | 0 | 40 - 0 |
When an end brings a name's count down to 0, that call was the outermost one, and only its length is added.
Self time needs no fix, since only one call is innermost at a time:
print(self_times(REC))
{'main': 0, 'f': 40}
Both passes are O(n) time for n events, and O(d + k) memory for stack depth d and k different functions.
In the editor, finish total_times(events) with that fix. stack holds each open call with its start time, and open_calls counts the open calls of each name.