KatInterview

Compute Per-Function Runtimes from a Profiler Event Log

Stacks & QueuesModel answer
MediumModel answerStacks & Queuesstacksimulationprofiling

Last 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 enters functionName at timestamp.
  • END functionName timestamp — execution leaves functionName at timestamp.

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

  1. 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.
  2. Compute the exclusive time for each function: the time the CPU was actually inside that function, not counting time spent in callees.
  3. Report the function(s) with the highest exclusive time. If several functions tie, return all of them in lexicographic order.
  4. Describe how your implementation handles each of the following anomalies:
    • A function that calls itself directly or indirectly (recursion / cycle).
    • A missing END event.
    • 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:

functioninclusiveexclusive
a125
b33
c44

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.