Skip to content

Instantly share code, notes, and snippets.

@dmi3coder
Last active November 28, 2019 08:16
Show Gist options
  • Save dmi3coder/f2369004b1dfe112aa8bfc1605fbd883 to your computer and use it in GitHub Desktop.
Save dmi3coder/f2369004b1dfe112aa8bfc1605fbd883 to your computer and use it in GitHub Desktop.
Example of cached decorator in Python
import time
cached_items = {}
def cached(func):
def wrapper(*args, **kwargs):
global cached_item
if func.__name__ not in cached_items:
cached_items[func.__name__] = func(*args, **kwargs)
return cached_items[func.__name__]
return wrapper
@cached
def intensive_task():
time.sleep(1.0)
return 10
start_time = time.time()
intensive_task()
print("--- %.8f seconds first execution ---" % (time.time() - start_time))
start_time = time.time()
intensive_task()
print("--- %.8f seconds second execution ---" % (time.time() - start_time))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment