我尝试为可以计算 Python 中另一个函数的运行时间的方法制作装饰器
def timer(func):
def smallfunctimer(*args,**kwargs):
res=func(*args,**kwargs)
tm=timeit.Timer(lambda:res)
print("Function time: ", tm)
return smallfunctimer
@timer
def deposit(self,amount):
self.balance+=amount
self.queue.append(BankTransaction(amount))
但是当我调用它的时候
ba=BankAccount(1,100)
ba.deposit(10000000)
我明白了:
Function time: <timeit.Timer object at 0x0281D370>
我如何获得以秒为单位的运行时间?
请您参考如下方法:
您创建了一个 timeit.Timer() instance ;您需要在该实例上调用一个方法才能实际运行代码:
print("Function time: ", tm.timeit(1000))
会给你运行该函数 1000 次所花费的时间。
