Last active
July 27, 2017 03:13
-
-
Save jian-en/0a07919500a0954f1b8bef6e5449a55d to your computer and use it in GitHub Desktop.
Usage of lru_cache
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 | |
import functools | |
def clock(func): | |
@functools.wraps(func) # relace with orig func's __name__ and __doc__ | |
def clocked(*args, **kwargs): | |
t0 = time.time() | |
result = func(*args, **kwargs) | |
elapsed = time.time() - t0 | |
name = func.__name__ | |
arg_lst = [] | |
if args: | |
arg_lst.append(', '.join(repr(arg) for arg in args)) | |
if kwargs: | |
pairs = ['%s=%r' % (k, w) for k, w in sorted(kwargs.items())] | |
arg_lst = ', '.join(pairs) | |
arg_str = ', '.join(arg_lst) | |
print('[%0.8fs] %s(%s) -> %r' % (elapsed, name, arg_str, result)) | |
return result | |
return clocked | |
@clock | |
def factorial(n): | |
return 1 if n < 2 else n * factorial(n - 1) | |
@functools.lru_cache() # if without, performance goes down | |
@clock | |
def fibonacci(n): | |
if n < 2: | |
return n | |
return fibonacci(n - 2) + fibonacci(n - 1) | |
if __name__ == '__main__': | |
print(fibonacci(6)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment