Created
February 8, 2021 07:32
-
-
Save saif-mahmud/793735279ebd367ea1855470c5bdd33f to your computer and use it in GitHub Desktop.
Python Class for Logging Execution Time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
import time | |
import numpy as np | |
class TimeLogger(): | |
def __init__(self, log_level="INFO"): | |
self.data_dict = dict() | |
self.logger = logging.getLogger(__name__) | |
self.logger.setLevel(log_level) | |
handler = logging.StreamHandler() | |
formatter = logging.Formatter(fmt="%(asctime)s.%(msecs)03d %(levelname)s -- %(message)s", | |
datefmt='%Y-%m-%d %H:%M:%S') | |
handler.setFormatter(formatter) | |
self.logger.addHandler(handler) | |
def timed(self, fn, *args, description=None, verbose=False, **kwargs): | |
if not description: | |
description = fn.__name__ | |
start = time.time() | |
result = fn(*args, **kwargs) | |
duration = time.time() - start | |
if verbose: | |
self.logger.info("[{}] Elapsed Time : {} sec".format(description, round(duration, 5))) | |
if description not in self.data_dict.keys(): | |
self.data_dict[description] = list() | |
self.data_dict[description].append(duration) | |
return result | |
def summary(self): | |
for description, durations in self.data_dict.items(): | |
print(f'[{description}] Avg. Elapsed Time : {np.mean(np.array(durations)):.5f} sec') | |
if __name__ == '__main__': | |
# Example Usage | |
def func(a, b): | |
time.sleep(1.5) | |
return a + b, a - b | |
t_log = TimeLogger() | |
for i in range(1, 10): | |
res = t_log.timed(func, i, i + 5, description='Operation on Integers', verbose=True) | |
# print(res) | |
t_log.summary() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample Output: