defmemoize(func): cache = {} defwrapper(*args): if args in cache: return cache[args] else: result = func(*args) cache[args] = result return result return wrapper
@memoize deffibonacci(n): if n <= 1: return n else: return fibonacci(n-1) + fibonacci(n-2)
计时器
记录函数运行时长。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
import time
deftiming_decorator(func): defwrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() print(f"Function {func.__name__} took {end_time - start_time} seconds to run.") return result return wrapper
@timing_decorator defmy_function(): # some code here time.sleep(1) # simulate some time-consuming operation return