Created
February 27, 2020 00:13
-
-
Save ericklarac/a839b24ea72a7d76b02644f2e9d88a75 to your computer and use it in GitHub Desktop.
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
# Erick Lara C. | @ericklarac | |
import time, datetime | |
class Timer(): | |
"""docstring for Timer.""" | |
def __init__(self): | |
self.ns_to_s = lambda x: x/1_000_000_000 | |
def __call__(self, f): | |
def wrapper(*args, **kwargs): | |
start = time.perf_counter_ns() | |
# Execute function | |
f(*args, **kwargs) | |
end = time.perf_counter_ns() | |
exp_time = self.ns_to_s(end-start) | |
print(f'Experiment elapsed time - {str(datetime.timedelta(seconds=exp_time))}') | |
return wrapper | |
# Decorator on function | |
@Timer() | |
def print_list_with_delay(a, b): | |
for i in a: | |
print(i) | |
time.sleep(2) | |
for i in b: | |
print(i) | |
print_list_with_delay(["y", "z"], ["a", "b"]) | |
# Decorator inside a class | |
class GA: | |
def __init__(self): | |
pass | |
@Timer() | |
def run_experiment(self, name): | |
print(name) | |
time.sleep(2) | |
print("Finished") | |
ga = GA() | |
ga.run_experiment("GA-Test1") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment