Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Write a Decorator to Time Function Execution

Create a reusable decorator that measures a function's execution time and exposes it via a wrapper attribute.

Python practice15 minDecorators FundamentalsIntermediateLast updated April 15, 2026

Problem statement

In this lesson you will implement a decorator named timeit. The decorator should: - Measure how long the wrapped function takes to run (use time.perf_counter for high resolution timing). - Store the measured duration (a float number of seconds) on the wrapper function as an attribute named last_duration. - Preserve the wrapped function's __name__ and __doc__ (use functools.wraps). - Return the wrapped function's original return value unchanged. - Ensure last_duration exists on the wrapper even before the first call (initialize to None). You must not change the decorated function's signature or behavior aside from adding the timing side-effect. The tests will call the decorated functions and inspect their return values and the last_duration attribute.

Task

Implement a decorator @timeit that times a wrapped function and stores the duration (in seconds) on the wrapper as last_duration, while preserving the original function's metadata and behavior.

Examples

Basic usage

Input

add(1, 2)

Output

3

After decorating add with @timeit, calling add(1, 2) returns 3 and add.last_duration contains the execution time as a float.

Input format

Each test expression will be evaluated in the environment after your code runs. Use the decorated functions directly (e.g., add(2, 3)).

Output format

Each test expects the evaluated expression's value; for booleans use True/False, for strings their exact value, etc.

Constraints

Use only the Python standard library. The decorator must use functools.wraps and time.perf_counter. Do not print from the decorator or the wrapped functions; expose timing via wrapper.last_duration.

Samples

Sample 1

Input

add(4, 5)

Output

9

The decorated add returns the correct sum; timing is stored on add.last_duration (not printed).