Time Any Function

Medium ⏱ 12 min 45% acceptance ★★★★☆ 4.2
Write timed(func) decorating a function so it returns a tuple (result, elapsed_seconds) measured with time.perf_counter around the call. Discussion point: changing a function's return shape is invasive — real profilers log instead — but it makes the mechanics visible here.

Examples

Example 1
Input
@timed applied to slow_add; slow_add(2, 3)
Output
(5, 0.0001...)
Explanation

The wrapper measured and bundled the timing.

Constraints

  • Use perf_counter, not time.time.
  • Preserve the wrapped name with wraps.

Topics

Decoratorstiming

Companies

DatadogNew RelicDynatrace

Hints

Hint 1

Capture start before, subtract after.

Hint 2

Return (result, elapsed).

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.