内容中心

2026年热门的MGS通风软管厂家精选-陕西裕华永赫航宇科技有限公司

To solve this problem, we need to create a class-based decorator in Python that measures the execution time of a function. The decorator should have an option to log the result to a file instead of printing it to the console.

Approach

  1. Class-Based Decorator: Use a class to implement the decorator, which allows us to handle both cases where the decorator is used with or without arguments.
  2. Metadata Preservation: Use functools.update_wrapper to preserve the original function's metadata (like name and docstring).
  3. Execution Time Measurement: Use time.perf_counter() for high-resolution timing to accurately measure the execution time of the function.
  4. Logging Option: Provide an option to log the execution time to a file. If a filename is provided, the result is appended to the file; otherwise, it is printed to the console.

Solution Code

import time
import functools

class ExecutionTimer:
    def __init__(self, func_or_logfile=None, log_file=None):
        """
        Initialize the ExecutionTimer decorator.

        Args:
            func_or_logfile: Either the function to decorate (when no arguments are passed) or the log file path.
            log_file: Optional log file path (used when func_or_logfile is not a function).
        """
        if callable(func_or_logfile):
            # Case: Decorator used without arguments (@ExecutionTimer)
            self.func = func_or_logfile
            self.log_file = None
            functools.update_wrapper(self, self.func)
        else:
            # Case: Decorator used with arguments (@ExecutionTimer(log_file="path"))
            self.log_file = func_or_logfile if log_file is None else log_file
            self.func = None

    def __call__(self, *args, **kwargs):
        """
        Execute the decorated function and measure its execution time.

        Returns:
            The result of the decorated function.
        """
        if self.func is None:
            # Wrap the function (called when decorator has arguments)
            self.func = args[0]
            functools.update_wrapper(self, self.func)
            return self
        else:
            # Measure execution time
            start_time = time.perf_counter()
            result = self.func(*args, **kwargs)
            end_time = time.perf_counter()
            elapsed_time = end_time - start_time

            # Format the result message
            message = f"Function '{self.func.__name__}' executed in {elapsed_time:.6f} seconds\n"

            # Log to file or print to console
            if self.log_file:
                with open(self.log_file, 'a') as f:
                    f.write(message)
            else:
                print(message, end='')

            return result

# Example Usage
@ExecutionTimer
def test_function_1():
    time.sleep(0.5)
    print("Test function 1 completed.")

@ExecutionTimer(log_file="execution_logs.txt")
def test_function_2(n):
    time.sleep(n)
    print(f"Test function 2 completed with n={n}.")

if __name__ == "__main__":
    test_function_1()
    test_function_2(0.3)
    test_function_2(0.7)

Explanation

  1. Initialization: The __init__ method handles two cases:

    • When the decorator is used without arguments (e.g., @ExecutionTimer), it directly takes the function to decorate and sets the log file to None.
    • When the decorator is used with arguments (e.g., @ExecutionTimer(log_file="execution_logs.txt")), it sets the log file path and leaves the function as None until the function is passed to __call__.
  2. Execution: The __call__ method:

    • If the function is not set (decorator with arguments), it wraps the function and returns the instance.
    • If the function is set, it measures the execution time using time.perf_counter(), computes the elapsed time, and either logs the result to the specified file or prints it to the console.

This approach ensures that the decorator is flexible, easy to use, and preserves the original function's metadata. The use of time.perf_counter() provides accurate timing for both short and long-running functions. The logging option allows for persistent storage of execution times, which is useful for debugging and performance analysis.

陕西裕华永赫航宇科技有限公司

陕西裕华永赫航宇科技有限公司



作者声明:本文包含人工智能生成内容。

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?