回答
Bravian回答
方法一:
import time
class NumberList(object):
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.end = time.time()
print("函数执行 %d 毫秒" % (self.end - self.start))
def func(self, number):
li = [1, 2, 4]
if number < 4:
return li[number - 1]
else:
if number > 3:
return (self.func(number - 1)
+ self.func(number - 2)
+ self.func(number - 3))
with NumberList() as n:
print(n.func(1000))
方法二:
import time
import contextlib
@contextlib.contextmanager
def timing():
start = time.time()
yield None
end = time.time()
print("函数执行时间是%d毫秒" % (end - start))
def func(number):
li = [1, 2, 4]
if number < 4:
return li[number - 1]
else:
if number > 3:
return func(number - 1) + func(number - 2) + func(number - 3)
with timing():
print(func(30))
(0)