Compute Per-Function Runtimes from a Profiler Event Log
Stacks & QueuesModel answerLast updated
Parse a time-ordered sequence of START/END events, compute inclusive and exclusive runtimes per function, and identify the most expensive function by self-time.
Profiler Log Analyzer
A single-threaded program emits a trace log as it runs. Each line is one of two event types:
START functionName timestamp— execution entersfunctionNameattimestamp.END functionName timestamp— execution leavesfunctionNameattimestamp.
Events arrive in timestamp order, and calls are nested like a normal call stack (a child must finish before its parent can continue). Timestamps are integers and represent points in time, so a function that starts at t=2 and ends at t=5 ran for 3 units.
Your task
- Compute the inclusive time for each function: the total wall-clock duration from when it was entered to when it returned, including time spent in any functions it called.
- Compute the exclusive time for each function: the time the CPU was actually inside that function, not counting time spent in callees.
- Report the function(s) with the highest exclusive time. If several functions tie, return all of them in lexicographic order.
- Describe how your implementation handles each of the following anomalies:
- A function that calls itself directly or indirectly (recursion / cycle).
- A missing
ENDevent. - A function that never returns (appears to run forever).
Example
START a 0
START b 2
END b 5
START c 6
END c 10
END a 12
Expected timing table:
| function | inclusive | exclusive |
|---|---|---|
| a | 12 | 5 |
| b | 3 | 3 |
| c | 4 | 4 |
a has inclusive time 12 and exclusive time 12 − 3 − 4 = 5. The slowest function by exclusive time is a.
What to produce
- The full timing table.
- The name(s) of the slowest function(s).
- A brief explanation of how each anomaly is detected and handled.
- Working code with a note on time and space complexity.
Hints
Hint 1
Think about what data structure naturally mirrors a call stack. When you see a START event, push something onto it; when you see END, pop. What information do you need to store per frame to reconstruct both timing numbers?
Hint 2
Exclusive time = a frame's total duration minus the combined duration of every direct child. If you track child_time on each stack frame and accumulate it as children finish, you never need to revisit events.
Hint 3
For recursion and cycles, the risk is double-counting inclusive time. Consider counting inclusive time only when the outermost invocation of a function exits — track how many frames for a given function are currently live on the stack.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A single-threaded trace is exactly a call stack replayed in time order. The cleanest way to compute both timing numbers is to simulate that stack directly rather than building a call graph.
Core algorithm
Maintain an explicit stack of frames. Each frame holds:
- the function name,
- the timestamp when it was pushed,
- a running
child_timeaccumulator.
On START f t: push a new frame for f.
On END f t: pop the top frame. Its duration is t − frame.start. Its exclusive time is duration − frame.child_time. Add duration to the parent frame's child_time (if one exists), so the parent can later subtract it from its own self-time.
This gives exclusive time in a single O(1) operation per event. Every unit of time is attributed to exactly one function: whoever is on top of the stack at that moment.
Inclusive time and recursion
Naively summing every frame's duration double-counts recursive calls — the outer a already contains the inner a. The fix is to credit inclusive time only when the outermost invocation of a function exits.
Keep a counter active[f] — the number of frames for f currently live on the stack — and record outer_start[f] when active[f] goes from 0 to 1. When active[f] drops back to 0, add now − outer_start[f] to inclusive[f]. Inner frames are completely contained within that window, so there's no double-counting.
A recursive call is detectable at push time: if active[f] > 0, it's recursion. If the top of the stack is also f, it's direct recursion; otherwise it's a cycle, and the stack slice from the previous f upward reveals the chain.
Handling malformed traces
Missing END events. When an END f arrives but f is not at the top of the stack, check whether f is deeper in the stack (active[f] > 0). If so, implicitly close every frame above it at the current timestamp, flag them as incomplete, then close f normally. If f isn't on the stack at all, it's an orphan END — record it and skip it. Because we check active[f] before doing anything else, no stack scan is needed; the amortized cost stays O(1) per event.
Never-returning functions. No analysis of a finite log can prove a function would never return — that's undecidable in general. In practice: at end of input, close all still-open frames at a configurable cutoff (end_time if supplied, otherwise the last observed timestamp) and mark their timings as lower bounds. Flag any frame whose open duration exceeds a configurable hang_threshold as a probable hang. In a live system, a watchdog thread periodically checks whether the top-of-stack frame has been running longer than the threshold.
Slowest function and ties
After processing all events, scan exclusive for the maximum value and collect all functions that match it. Return them sorted lexicographically so the result is deterministic.
Complexity
- Time: O(n) for n events. Each frame is pushed and popped once; all dictionary operations are O(1). Sorting the k distinct functions adds O(k log k), but k ≤ n so the overall bound remains O(n log n) in the worst case and O(n) when there are no ties.
- Space: O(d + k), where d is the maximum call-stack depth and k is the number of distinct functions.
Common mistakes
- Using
end − start + 1vs.end − start: confirm the timestamp convention before writing any arithmetic. - Accumulating inclusive time from every frame instead of only the outermost one — this breaks as soon as any recursion appears.
- Forgetting to register a function in both dictionaries on first sight, so functions with zero total time disappear from the output.
- Silently discarding malformed lines rather than logging them; callers need to know which numbers are estimates.
Code
from collections import defaultdict
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class Frame:
name: str
start: int
child_time: int = 0
def analyze_profile(
lines: list[str],
end_time: Optional[int] = None,
hang_threshold: Optional[int] = None,
) -> dict:
"""
Parse a profiler event log and return per-function timings.
Returns:
table: {fn: {"inclusive": int, "exclusive": int}}
slowest: sorted list of functions tied for max exclusive time
max_exclusive: that maximum value, or None if the log is empty
anomalies: list of (kind, detail) tuples describing repairs/issues
"""
inclusive: dict[str, int] = defaultdict(int)
exclusive: dict[str, int] = defaultdict(int)
active: dict[str, int] = defaultdict(int) # live frame count per function
outer_start: dict[str, int] = {}
stack: list[Frame] = []
anomalies: list[tuple] = []
last_ts: Optional[int] = None
def close_top(t: int) -> Frame:
"""Pop the top frame and attribute its time."""
frame = stack.pop()
dur = t - frame.start
exclusive[frame.name] += dur - frame.child_time
if stack:
stack[-1].child_time += dur
active[frame.name] -= 1
if active[frame.name] == 0:
inclusive[frame.name] += t - outer_start.pop(frame.name)
return frame
for lineno, raw in enumerate(lines, 1):
parts = raw.split()
if not parts:
continue
if len(parts) != 3 or parts[0] not in ("START", "END"):
anomalies.append(("malformed_line", (lineno, raw.strip())))
continue
kind, name, ts_str = parts
try:
t = int(ts_str)
except ValueError:
anomalies.append(("malformed_line", (lineno, raw.strip())))
continue
if last_ts is not None and t < last_ts:
anomalies.append(("time_went_backwards", (lineno, raw.strip())))
continue
last_ts = t
# Ensure function appears in output table even with zero time.
inclusive.setdefault(name, 0)
exclusive.setdefault(name, 0)
if kind == "START":
if active[name] > 0:
# Detect recursion vs. cycle.
if stack and stack[-1].name == name:
anomalies.append(("direct_recursion", name))
else:
cycle_depth = next(
(i for i, f in enumerate(stack) if f.name == name), None
)
cycle_path = [f.name for f in stack[cycle_depth:]] + [name]
anomalies.append(("cycle", " -> ".join(cycle_path)))
else:
outer_start[name] = t
active[name] += 1
stack.append(Frame(name=name, start=t))
else: # END
if not stack:
anomalies.append(("orphan_end", (lineno, name, t)))
continue
if stack[-1].name != name:
if active[name] > 0:
# Close frames above the matching one implicitly.
while stack and stack[-1].name != name:
dropped = close_top(t)
anomalies.append(("implicit_close", (dropped.name, t)))
close_top(t)
else:
anomalies.append(("orphan_end", (lineno, name, t)))
else:
close_top(t)
if hang_threshold is not None and stack:
top = stack[-1]
if t - top.start > hang_threshold:
anomalies.append(("possible_hang", (top.name, top.start, t)))
# Close frames still open at end of input.
cutoff = end_time if end_time is not None else (last_ts or 0)
while stack:
dropped = close_top(cutoff)
anomalies.append(("unclosed_at_eof", (dropped.name, cutoff)))
table = {
fn: {"inclusive": inclusive[fn], "exclusive": exclusive[fn]}
for fn in inclusive
}
if not table:
return {"table": {}, "slowest": [], "max_exclusive": None, "anomalies": anomalies}
max_excl = max(v["exclusive"] for v in table.values())
slowest = sorted(fn for fn, v in table.items() if v["exclusive"] == max_excl)
return {
"table": table,
"slowest": slowest,
"max_exclusive": max_excl,
"anomalies": anomalies,
}
# --- Example ---
if __name__ == "__main__":
log = [
"START a 0",
"START b 2",
"END b 5",
"START c 6",
"END c 10",
"END a 12",
]
result = analyze_profile(log)
print("Timings:")
for fn, times in sorted(result["table"].items()):
print(f" {fn}: inclusive={times['inclusive']}, exclusive={times['exclusive']}")
print(f"Slowest: {result['slowest']} (exclusive={result['max_exclusive']})")
Edge cases to call out in an interview
- Empty log → return an empty table, no slowest function.
- Zero-length calls (
START f 5/END f 5) → time is 0, function still appears. - All functions tie → return all names sorted lexicographically.
- Timestamps going backwards → reject and flag; negative durations are nonsensical.