easy +10 pts

Timer Context Manager

Build a context manager that times code blocks and stores elapsed time.

Write a context manager class `Timer` that measures the wall-clock time of a block of code executed inside a `with` statement. - The class must be initialized with no arguments: `Timer()`. - When entering the `with` block, record the current time. - When exiting the `with` block, compute the elapsed time in seconds (float) and store it in the attribute `elapsed`. - The attribute `elapsed` must be available immediately after the `with` block ends. - The context manager must suppress no exceptions; it should behave like a normal context manager. - The object returned by `__enter__` should be the `Timer` instance itself, so that the `with` statement can bind it as a variable. Implement the class `Timer` with the methods `__enter__` and `__exit__`. You may use any standard library module (e.g., `time`).

Constraints

The input is not provided; the class is used with a with-block. Elapsed time will be a non-negative float. The test will measure the correctness of storing elapsed time and that the with-block executes normally.

Example

# Example usage:
import time

t = Timer()
with t:
    time.sleep(0.01)

assert t.elapsed >= 0.01

# Another example:
t2 = Timer()
with t2:
    pass
assert t2.elapsed >= 0.0
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use time.perf_counter() or time.time() to get the current time before and after the block.
In __enter__, store the start time in an instance attribute, e.g., self.start, and return self.
In __exit__, compute elapsed and assign to self.elapsed.
Remember __exit__ should return None (or False) to not suppress exceptions.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.