Last active
November 28, 2019 08:16
-
-
Save dmi3coder/f2369004b1dfe112aa8bfc1605fbd883 to your computer and use it in GitHub Desktop.
Example of cached decorator 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
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