Last active
May 1, 2020 02:06
-
-
Save miracleyoo/92ab52c5f59c20b176b5eed025ad10da to your computer and use it in GitHub Desktop.
[Timer and Log Functions] #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
import functools | |
import time | |
class Timer(object): | |
def __init__(self, name=None): | |
self.name = name | |
def __enter__(self): | |
self.t_start = time.time() | |
def __exit__(self, type, value, traceback): | |
print("==> [%s]:\t" % self.name, end="") | |
self.time_elapsed = time.time() - self.t_start | |
print("Elapsed Time: %s (s)" % self.time_elapsed) | |
def log(*snippets, end=None, tag="INFO"): | |
print(f"==> [{tag}]", time.strftime("[%Y-%m-%d %H:%M:%S]", time.localtime()) + " " + "".join([str(s) for s in snippets]), | |
end=end) | |
def tic_toc(func): | |
"""Print the time consumption of a certain function when a it is excuted. | |
Args: | |
func: An function. | |
""" | |
@functools.wraps(func) | |
def wrapper(*args, **kw): | |
tic = time.time() | |
res = func(*args, **kw) | |
print("==> [%s] executed in %.4f s." % (func.__name__ ,time.time() - tic)) | |
return res | |
return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment