Measure Function Duration (Profiling Wrapper)

intermediate
By FrontendAtlas Editorial · Updated Oct 10, 2026
Implement measure(fn, now?) to profile execution time. It should run a function, measure the duration using the provided clock, and return { result, durationMs }. It must support both sync and async functions (return a Promise in all cases).

Arguments

  • fn: () => any | Promise<any> — Function to execute and measure.
  • now: () => number — Optional clock (defaults to performance.now or Date.now).

Returns

Promise<{ result: any, durationMs: number }> — The function result plus elapsed time in ms.

Solution idea

Capture a start time, execute the function, then capture an end time after it finishes. Wrap the result in Promise.resolve so both sync and async paths are handled consistently.

Examples
await measure(() => doWork())

await measure(async () => await fetchData(), () => 0)