Create Timing Functions With Decorators in Python

Create Timing Functions With Decorators in Python

Decorators are frequently used helpful tools in Python. We can perform the operations we want before and after executing the functions with decorators.

This article will explain creating timing functions with decorators using Python’s time module.

Create Timing Functions With Decorators in Python

The time module provides various time-related functions. This module’s time() function returns the number of seconds passed since the epoch (January 1, 1970, 00:00:00).

To calculate the executing time of a function, we can use this module with decorators.

Decorators allow modifying the behavior of function or class in Python. They allow the programmer to wrap another function to extend the wrapped function’s behavior without permanently modifying it.

First, the time module is imported in the example below. Then, the timer function is defined.

This function will be used as a decorator.

The main_func is the function whose execution time will be calculated. It just performs a loop operation here as an example.

The start and end values are calculated within the timer function with the time() command before and after main_func is executed. The difference between these two values gives the execution time of the main_func function.

from time import time

def timer(function):
    def wrapper(*args, **kwargs):
        start = time()
        function(*args, **kwargs)
        end = time()
        print(f'It took {(end-start):.3f} seconds')

    return wrapper

@timer
def main_func():
    for i in range(1000000):
        continue

main_func()

timing

Author: Yahya Irmak
Yahya Irmak avatar Yahya Irmak avatar

Yahya Irmak has experience in full stack technologies such as Java, Spring Boot, JavaScript, CSS, HTML.

LinkedIn

Related Article - Python Decorator

  • Python Decorator Order
  • Use Python Decorators to Retry Code Blocks
  • Implement Multiple Decorators in Python
  • Class Decorator in Python