w3resource

Create a Python Class-based Decorator to Log method execution time

Write a Python program to create a class-based decorator that logs the execution time of methods.

The task is to develop a Python program that creates a class-based decorator to log the execution time of methods. This decorator will be applied to methods to measure and record how long they take to execute, aiding in performance monitoring and optimization. The program will define a decorator class that can be easily reused across different methods and classes, providing a standardized way to track execution times.

Sample Solution:

Python Code :

import time  # Import the time module to measure execution time

class LogExecutionTime:  # Define a class for the decorator
    def __init__(self, func):  # Initialize the decorator with the function to be decorated
        self.func = func  # Store the function to be decorated

    def __get__(self, instance, owner):  # Define the descriptor method to handle instance methods
        return lambda *args, **kwargs: self(instance, *args, **kwargs)  # Return a lambda that passes the instance

    def __call__(self, *args, **kwargs):  # Make the class instance callable
        instance = args[0]  # Extract the instance from the arguments
        start_time = time.time()  # Record the start time
        result = self.func(instance, *args[1:], **kwargs)  # Call the original function with its arguments
        end_time = time.time()  # Record the end time
        execution_time = end_time - start_time  # Calculate the execution time
        print(f"Execution time of {self.func.__name__}: {execution_time:.4f} seconds")  # Log the execution time
        return result  # Return the result of the original function call

# Example usage:

class ExampleClass:  # Define an example class to demonstrate the decorator
    @LogExecutionTime  # Apply the decorator to the method
    def example_method(self):  # Define a method in the class
        for _ in range(1000000):  # A sample computation to add some delay
            pass  # Do nothing

# Instantiate the example class and call the decorated method
example = ExampleClass()  # Create an instance of the ExampleClass
example.example_method()  # Call the decorated method to see the execution time log

Output:

Execution time of example_method: 0.0139 seconds

Explanation:

  • The code defines a class-based decorator, "LogExecutionTime", to measure and log the execution time of instance methods. The decorator uses the descriptor protocol to correctly handle instance methods, ensuring that the 'self' parameter is passed. When a decorated method is called, it logs the time taken for its execution.
  • Imports time: Used to measure execution time.
  • LogExecutionTime class: A decorator that logs execution time.
  • init: Initializes with the function to be decorated.
  • get: Ensures the instance ('self') is correctly passed to the method.
  • call: Measures and logs the execution time of the decorated method.
  • ExampleClass: Demonstrates the usage of the "LogExecutionTime" decorator.
  • example_method: A method with added delay to test the decorator.
  • Testing: An instance of "ExampleClass" is created and the decorated method is called, logging its execution time.

Python Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Implement a Multi-threaded Web Scraper that respects robots.txt rules.
Next: Develop a Custom Iterator for Tree data structures in Python

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/advanced/create-a-python-class-based-decorator-to-log-method-execution-time.php