Self time counts the samples with a function on top, total time the samples with it anywhere
A profiler reports two times for each function, and both come from counting the samples.
Predict
Samples come every 10 ms, and each stands for the 10 ms after it. main is in all 7 that count, but on top in only one. What are its self and total time?
Here are the eight samples again, drawn as stacks. Each sample stands for the 10 ms until the next one. The last one, at 70, only closes what's still open, so it stands for no time:
The eight samples
main
0
mainload
10
mainloadparse
20
mainloadparse
30
mainsave
40
mainsave
50
mainsave
60
main
70
Function
On top
In the stack
Self time
Total time
main
1
7
10 ms
70 ms
load
1
3
10 ms
30 ms
parse
2
2
20 ms
20 ms
save
3
3
30 ms
30 ms
Profilers report these two numbers for each function. Python's cProfile calls them tottime and cumtime.
Self time (tottime) is the time spent in the function itself, leaving out the functions it calls. A sample with the function on top adds 10 ms of it.
Total time (cumtime) runs from each call's start to its end, with the functions it calls included. A sample with the function anywhere in the stack adds 10 ms of it.
The events give the same numbers, with a stack.
From the events, the innermost open call owns each stretch of time
Between two events, exactly one call is innermost, the one on top of the stack. It owns that stretch of time:
def self_times(events): own = {} # names of the open calls, innermost last stack = [] # time of the previous event last = None for time, kind, name in events: own.setdefault(name, 0) if stack: own[stack[-1]] += time - last if kind == "start": stack.append(name) else: stack.pop() last = time return ownprint(self_times(EVENTS))
{'main': 10, 'load': 10, 'parse': 20, 'save': 30}
The same stack is the core of Exclusive Time of Functions, which is on the compiled LeetCode list for Anthropic (1 source). LeetCode's logs count an end time differently, though.
The table above came straight from the samples, with no events at all. In the editor, write times(samples) to do the same: return the self times and the total times, as two dicts, for the eight samples in SAMPLES.
Pick an answer above to see the rest
Instructions
1
Write times(samples): two dicts, self time and total time. Each sample stands for the time until the next one, and the last sample stands for none.
2
Self time goes to the name on top. Total time goes once to each name in the stack, even a name that's in it twice.