TimeLogger
The TimeLogger is a Python class designed to function as a decorator, allowing you to measure and log the execution time of functions. This is particularly useful for performance monitoring and debugging.
Implementation
The TimeLogger class is implemented as follows:
import time
class TimeLogger:
def __init__(self, func):
def logger(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"Calling {func.__name__}: {time.time() - start:.5f}")
return result
self._logger = logger
def __call__(self, *args, **kwargs):
return self._logger(*args, **kwargs)
Key Features
-
Initialization: The constructor (
__init__) of theTimeLoggerclass takes a function as its argument. It defines an inner functionloggerthat wraps the original function to measure its execution time. -
Logging Execution Time: The
loggerfunction records the start time, calls the original function, and then calculates and prints the time taken for the function call. -
Callable Instances: By overriding the
__call__method, instances ofTimeLoggercan be called like regular functions. This method delegates the call to the_loggerfunction, which is a callable attribute of the instance.
Usage
To use the TimeLogger class as a decorator, you simply prefix a function definition with @TimeLogger. Here is an example:
@TimeLogger
def calculate_sum(n):
return sum(range(n))
result = calculate_sum(100_000)
# [output: Calling calculate_sum: 0.00181](https://livebook.manning.com/book/python-how-to/chapter-10/269)
Important Note
When a function is decorated with TimeLogger, it is transformed into an instance of the TimeLogger class. This means that the decorated function is no longer a standard function but an instance object. For example:
print(calculate_sum)
# [output: <__main__.TimeLogger object at 0x7fe8180de710>](https://livebook.manning.com/book/python-how-to/chapter-10/269)
Despite this transformation, the instance can still be called like a function due to the overridden __call__ method, which ensures that the instance behaves like the original function.
The TimeLogger class provides a simple yet effective way to monitor the performance of functions by logging their execution time, making it a valuable tool for developers looking to optimize their code.
FAQ (Frequently asked questions)
What is a TimeLogger in Python?
How does the TimeLogger class work?
How do you use the TimeLogger class as a decorator?
What is the output of using TimeLogger on the calculate_sum function?