Build a with-Statement Timer

Hard ⏱ 18 min 26% acceptance ★★★★☆ 4.4
Write a class Timer usable as with Timer() as t: that records time.perf_counter() on entry and sets t.elapsed (seconds) on exit — even when the body raises (do not suppress the exception; return False/None from __exit__).

Examples

Example 1
Input
with Timer() as t:\n    work()\nprint(t.elapsed > 0)
Output
True
Explanation

__exit__ always stamps the elapsed time.

Constraints

  • Implement __enter__ and __exit__.
  • Exceptions must propagate.

Topics

Exception Handlingcontext managers

Companies

GoogleNetflixDatadog

Hints

Hint 1

__enter__ returns self so "as t" binds the instance.

Hint 2

__exit__(self, exc_type, exc, tb) computes elapsed unconditionally.

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