Skip to content

About

Write a decorator that prints how long the wrapped function takes to run

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 

Repository files navigation

Timer Decorator

Premise

Write a decorator (Python) / higher-order function (JS) called timer that wraps another function. When the wrapped function runs, the timer should print how long it took, then return the original function's return value unchanged.

The point of this exercise is to practice decorating a function — adding behavior around a function without modifying its code.

Python

Use the @timer decorator syntax:

@timer
def slow_add(a, b):
    time.sleep(0.5)
    return a + b

slow_add(2, 3)
# prints something like: "slow_add took 0.5021 seconds"
# returns: 5

JavaScript

JS does not have stable decorator syntax, so wrap the function manually:

const timedSlowAdd = timer(function slowAdd(a, b) {
  // (pretend this is slow)
  return a + b;
});

timedSlowAdd(2, 3);
// prints something like: "slowAdd took 0.0001 seconds"
// returns: 5

Requirements

  • The print/console message must include the function name and the elapsed time.
  • The wrapped function must return the same value as the original.
  • It should work with any number of arguments.

Test Your Code

  • Python: python timer_tests.py
  • JS: node timerTests.js

Stretch

Extend timer so it accepts a label argument — @timer("expensive call") (Python) or timer(fn, "expensive call") (JS) — and uses that label in the print output instead of the function name.

Stuck? Have a code error? Use the "4 Before Me" debugging checklist to help you solve it!

About

Write a decorator that prints how long the wrapped function takes to run

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages