Application of Decorators (2): time a function in Python

Timing a function is one way to evaluate its performance. This post demonstrates how to use decorator to time a function.

Timing a function Directly

It is very straightforward, if we want to time a function directly. The code snippet below demonstrate how to do it.

Timing a function Using Decorator

With decorator, the code for timing can be reused. Below is an example implementation of a timer decorator.

The example below demonstrates how the above decorator can be used to time functions.

def countdown(num: int) -> None:
while num > 0:
num -= 1
@timed
def func0(num: int=100000000) -> None:
countdown(num)
countdown(num)
@timed
def func1(num: int=100000000) -> None:
thread_1 = threading.Thread(target=countdown, args=(num,))
thread_2 = threading.Thread(target=countdown, args=(num,))
thread_1.start()
thread_2.start()
thread_1.join()
thread_2.join()
@timed
def func2(num: int=100000000) -> None:
process_1 = multiprocessing.Process(target=countdown, \
args=(num,))
process_2 = multiprocessing.Process(target=countdown, \
args=(num,))
process_1.start()
process_2.start()
process_1.join()
process_2.join()
>>> func0(10000000)
func0(10000000) takes 0.9984452724456787 seconds.
>>>
>>> func1(10000000)
func1(10000000) takes 1.1887896060943604 seconds.
>>>
>>> func2(10000000)
func2(10000000) takes 0.6226904392242432 seconds.
>>>

It is very interesting to see that multi-threading does not run faster. I will explain this in a different post.

Senior Software/Data Engineer