PracticeLevel 6: ProfessionalEx 146. Time a code block
0/150 Solved(0%)
Level 6Exercise #146

Time a code block

Create a context manager that prints elapsed seconds after the wrapped block, even if it raises.

What you’ll practice

This Level 6 exercise focuses on contextmanager in the Professional curriculum. Solve the challenge prompt above using clear, idiomatic Python and the relevant language or standard-library tools.

Relevant Python reference: contextlib — Context management.

Sample Test Cases

Example #1
Input:(lambda: [t := timer('build'), t.__enter__(), t.__exit__(None, None, None)][0] and 'ok')()
Output:prints elapsed time

Further Reading

Reference Solution

Reveal Reference Solution
def timer(label: str):
from contextlib import contextmanager
from time import perf_counter
@contextmanager
def _timer():
start = perf_counter()
try:
yield
finally:
print(f'{label}: {perf_counter()-start:.3f}s')
return _timer()
Pro Tips & Keyboard Shortcuts
Color Theme
Ctrl + K then T

Open VS Code Color Theme Quick Pick to select from 20 dark and light themes.

Editor SettingsCtrl + K

Open practice settings drawer to toggle line numbers, indenting, font size & hints.

Search MenuCtrl + /

Expand sidebar menu, focus search bar, and highlight search text instantly.

Focus Code Editor
Esc or Ctrl + `

Instantly highlight and focus code editor from anywhere, restoring cursor right where you left off.

Normal ViewEsc

Collapse sidebar and close all popups or settings drawers for clean focus view.

solution.py· Python 3.11 WASM