Last active
July 4, 2019 11:25
-
-
Save dakaugu/d01213ae54f304900f5e918dd07953ad to your computer and use it in GitHub Desktop.
Measure code execution time in Python
This file contains hidden or 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
# coding=utf-8 | |
import logging | |
import math | |
import time | |
from functools import wraps | |
logger = logging.getLogger(__name__) | |
class Timer: | |
""" | |
A timing util to measure code execution time in human readable | |
format for a snippet of code or method. | |
Usage: | |
with Timer() as t: | |
some code ... | |
print(t.runtime) | |
or | |
@time_it() | |
def some_func(): | |
some code ... | |
returns: "time taken by method.module method.name: x seconds x ms" | |
for raw timing use raw kwarg | |
ex: | |
with Timer(raw=True) as t: | |
some code ... | |
@time_it(raw=True) | |
def some_func(): | |
some code ... | |
returns: "time taken by method.module method.name: x.xxxx" | |
@dakaugu | |
""" | |
def __init__(self, raw=False): | |
self.runtime = 0 | |
self.raw = raw | |
def __enter__(self): | |
self.runtime = self.time_me() | |
return self | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
self.runtime = self.time_me(start_time=self.runtime, raw=self.raw) | |
@staticmethod | |
def time_me(start_time=None, raw=False): | |
if start_time: | |
elapsed_time = time.time() - start_time | |
if raw: | |
return elapsed_time | |
hours = math.floor(elapsed_time / 3600) | |
elapsed_time = elapsed_time - hours * 3600 | |
minutes = math.floor(elapsed_time / 60) | |
elapsed_time = elapsed_time - minutes * 60 | |
seconds = math.floor(elapsed_time) | |
elapsed_time = elapsed_time - seconds | |
ms = math.floor(elapsed_time * 1000) | |
micros = elapsed_time * 1000 * 1000 | |
if hours: | |
return "%d hours %d minutes %d seconds" % (hours, minutes, seconds) | |
elif minutes: | |
return "%d minutes %d seconds" % (minutes, seconds) | |
elif seconds: | |
return "%d seconds %d ms" % (seconds, ms) | |
elif ms: | |
return "%d ms" % ms | |
return "%d μs" % micros | |
return time.time() | |
def time_it(raw=False): | |
def dec(func): | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
with Timer(raw=raw) as t: | |
result = func(*args, **kwargs) | |
logger.info("time taken by %s %s: %s" % | |
(func.__module__, func.__name__, t.runtime)) | |
return result | |
return wrapper | |
return dec |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment