Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Challenge: Timing Decorator | Built-in and Real-World Decorators
Python Decorators Explained

bookChallenge: Timing Decorator

Measuring how long a function takes to execute is a common requirement when you want to optimize your code or simply understand its performance. In Python, the time module provides functions for working with time-related tasks. When creating a timing decorator, you can use time.time() to record the current time before the function runs and again after it finishes. By subtracting the start time from the end time, you obtain the elapsed time, which you can then print or log. This technique is especially useful for benchmarking or profiling your code without modifying the original function logic.

Oppgave

Swipe to start coding

Create a decorator that measures and prints how long a function takes to execute.

  • The decorator must use the time module to record the start and end time.
  • The decorator must print the function name and the elapsed time in seconds, formatted to six decimal places.
  • The decorator must return the result of the original function.

Løsning

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 4
single

single

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

close

bookChallenge: Timing Decorator

Sveip for å vise menyen

Measuring how long a function takes to execute is a common requirement when you want to optimize your code or simply understand its performance. In Python, the time module provides functions for working with time-related tasks. When creating a timing decorator, you can use time.time() to record the current time before the function runs and again after it finishes. By subtracting the start time from the end time, you obtain the elapsed time, which you can then print or log. This technique is especially useful for benchmarking or profiling your code without modifying the original function logic.

Oppgave

Swipe to start coding

Create a decorator that measures and prints how long a function takes to execute.

  • The decorator must use the time module to record the start and end time.
  • The decorator must print the function name and the elapsed time in seconds, formatted to six decimal places.
  • The decorator must return the result of the original function.

Løsning

Switch to desktopBytt til skrivebordet for virkelighetspraksisFortsett der du er med et av alternativene nedenfor
Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 4
single

single

some-alt