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

  1. Initialization: The constructor (__init__) of the TimeLogger class takes a function as its argument. It defines an inner function logger that wraps the original function to measure its execution time.

  2. Logging Execution Time: The logger function records the start time, calls the original function, and then calculates and prints the time taken for the function call.

  3. Callable Instances: By overriding the __call__ method, instances of TimeLogger can be called like regular functions. This method delegates the call to the _logger function, 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.