Skip to content

Instantly share code, notes, and snippets.

@K0NRAD
Created August 22, 2020 11:27
Show Gist options
  • Save K0NRAD/0a82c8ea85d033a36840b382e06e460f to your computer and use it in GitHub Desktop.
Save K0NRAD/0a82c8ea85d033a36840b382e06e460f to your computer and use it in GitHub Desktop.
a simple cache for time intensive operations
from datetime import datetime
from time import sleep
def memoice(func):
class MemoDict(dict):
def __init__(self, func):
super().__init__()
self.func = func
def __call__(self, *args):
return self[args]
def __missing__(self, key):
ret = self[key] = self.func(*key)
return ret
return MemoDict(func)
def timemessure(func):
class TimeMeassure:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
t = datetime.now()
ret = self.func(*args, **kwargs)
et = datetime.now() - t
print(f'Time elapsed (hh:mm:ss.ms) {et}')
return ret
return TimeMeassure(func)
n_calls = 0
@memoice
def time_expensive_function(x, y):
global n_calls
n_calls += 1
sleep(0.2)
return x * y
data = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] * 10
@timemessure
def run():
out = [time_expensive_function(x, y) for x, y in data if time_expensive_function(x, y) > 0]
print(out)
print(n_calls)
if __name__ == '__main__':
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment