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
- 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.
- Metadata Preservation: Use
functools.update_wrapperto preserve the original function's metadata (like name and docstring). - Execution Time Measurement: Use
time.perf_counter()for high-resolution timing to accurately measure the execution time of the function. - 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
-
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 toNone. - 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 asNoneuntil the function is passed to__call__.
- When the decorator is used without arguments (e.g.,
-
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.


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