A High Order Timer Function

Photo by JJ Ying on Unsplash

A high order function is a function that takes a function as an argument or returns a function.
One use case is when you want to do something more with your function without altering the passed-on function.

For example, if we want to time the execution of a function the not optimal way.

import timedef cubeit(x):
time.sleep(1)
return x * x * x
t_start = time.perf_counter()
res = cubeit(144)
t_end = time.perf_counter()
t_run = t_end - t_start
print(f'It took cubeit {t_run:.2f} sec to complete')
print(res)
It took cubeit 1.00 sec to complete
2985984

It’s not optimal! What if you want to perform the same task on another function.

The High order function approach, passing the function cubeit to our timer function.

import timedef timer_func(f):
def wrapper_timer(*args):
t_start = time.perf_counter()
res = f(*args)
t_end = time.perf_counter()
t_run = t_end - t_start
print(f'It took {f.__name__} {t_run:.2f} sec to complete')
return res
return wrapper_timer
def cubeit(x):
time.sleep(1)
return x * x * x
foo = timer_func(cubeit)
res = foo(144)
print(res)
It took cubeit 1.00 sec to complete
2985984

Well, this is cluttered! is there a neat way to achieve the same result?

Yes, the pythonic way of using decorators.

import timedef timer_func(f):
def wrapper_timer(*args):
t_start = time.perf_counter()
res = f(*args)
t_end = time.perf_counter()
t_run = t_end - t_start
print(f'It took {f.__name__} {t_run:.2f} sec to complete')
return res
return wrapper_timer
@timer_func
def cubeit(x):
time.sleep(1)
return x * x * x
res = cubeit(144)
print(res)
It took cubeit 1.00 sec to complete
2985984

Note that @timer_fun is equivalent to timer_fun(cubeit).
So, what else can I do with decorators, logging to an external file!

--

--

--

https://github.com/booletic

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

GIT ‘er done!

[IOS] “INVALID SWIFT_VERSION: COULD NOT PARSE VERSION COMPONENT FROM: ‘0 5’” ERROR WHEN DEPLOYING…

“Vault, Terraform & AWS Integration” : Fetching AWS access/secret keys dynamically from vault…

Configure A Site-to-Site VPN between Meraki and Oracle Cloud

Is the Government Digital Marketplace Making Procurement Worse or Better? Anecdotal Evidence

Salesforce Asynchronous Apex Future Method

The Machine Aspect of Tensors

GIF Converter with Mac Siri Shortcuts

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mansoor Aldosari

Mansoor Aldosari

https://github.com/booletic

More from Medium

Python Puzzles — Word Capitalization!

Weak references in Python

Make a Caesar’s cipher with Python

Ooohh Caesar Circle

Handling Dates in Python