Skip to content

Instantly share code, notes, and snippets.

@saif-mahmud
Created February 8, 2021 07:32
Show Gist options
  • Save saif-mahmud/793735279ebd367ea1855470c5bdd33f to your computer and use it in GitHub Desktop.
Save saif-mahmud/793735279ebd367ea1855470c5bdd33f to your computer and use it in GitHub Desktop.
Python Class for Logging Execution Time
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()
@saif-mahmud
Copy link
Author

Sample Output:

2021-02-08 13:24:59.953 INFO -- [Operation on Integers] Elapsed Time : 1.50175 sec
2021-02-08 13:25:01.455 INFO -- [Operation on Integers] Elapsed Time : 1.50173 sec
2021-02-08 13:25:02.957 INFO -- [Operation on Integers] Elapsed Time : 1.50161 sec
2021-02-08 13:25:04.459 INFO -- [Operation on Integers] Elapsed Time : 1.50173 sec
2021-02-08 13:25:05.961 INFO -- [Operation on Integers] Elapsed Time : 1.50175 sec
2021-02-08 13:25:07.462 INFO -- [Operation on Integers] Elapsed Time : 1.50171 sec
2021-02-08 13:25:08.965 INFO -- [Operation on Integers] Elapsed Time : 1.50175 sec
2021-02-08 13:25:10.467 INFO -- [Operation on Integers] Elapsed Time : 1.50174 sec
2021-02-08 13:25:11.969 INFO -- [Operation on Integers] Elapsed Time : 1.5016 sec
[Operation on Integers] Avg. Elapsed Time : 1.50171 sec

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment