Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import time
- import logging
- class Timer:
- def __init__(self, timed, logger=None):
- self.logger = logger
- self.timed = timed
- def __enter__(self):
- self.start = time.perf_counter()
- return self
- def __exit__(self, *args):
- self.end = time.perf_counter()
- self.interval = self.end - self.start
- if self.logger is not None:
- if self.interval < 0.01:
- self.logger.debug(f"{self.timed}: {self.interval:0.2E} sec.")
- else:
- self.logger.debug(f"{self.timed}: {self.interval:0.5f} sec.")
- # example usage with logging
- logging.basicConfig(
- handlers=[
- logging.StreamHandler(),
- # logging.FileHandler("logfile.log", mode='a', encoding='utf8')
- ],
- format='%(asctime)s %(levelname)s [%(module)s]: %(message)s')
- logger = logging.getLogger()
- logger.setLevel(logging.DEBUG)
- with Timer("Time", logger=logger) as t:
- # something you wanna time
- pass
- time.sleep(0.5)
- # You can also access the time as follow:
- print(t.interval)
Add Comment
Please, Sign In to add comment