Created
June 13, 2019 15:27
-
-
Save berdosi/e1583bf907217cf467fdcace537817e5 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
import time | |
def donothingDecorator(f): | |
""" Make a function returning some string return it prepended with the string's length. """ | |
def wrapper(*args, **kwargs): | |
#print("ogwell") | |
returnvalue = str(f(*args, **kwargs)) | |
return str(len(returnvalue)) + " " + returnvalue | |
return wrapper | |
@donothingDecorator | |
def returnStuff(n): | |
return str(n) | |
print(returnStuff("hello")) | |
cache = {} | |
def memoized(f): | |
""" Cache a function's return value, and use it, if available. """ | |
def wrapper(*args, **kwargs): | |
key = f.__name__ + str(args[0]) | |
if key in cache: | |
return cache[key] | |
else: | |
cache[key] = f(*args, **kwargs) | |
return cache[key] | |
return wrapper | |
def fib1(n): | |
if n > 2: | |
return fib1(n-1) + fib1(n-2) | |
return 1 | |
@memoized | |
def fib2(n): | |
if n > 2: | |
return fib2(n-1) + fib2(n-2) | |
return 1 | |
# benchmark | |
n = 30 | |
runcount = 10 | |
t1 = time.time() | |
for i in range(runcount): | |
fib1(n) | |
t2 = time.time() | |
for i in range(runcount): | |
fib2(n) | |
t3 = time.time() | |
print(t2 - t1) | |
print(t3 - t2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment