无法使用装饰器打印功能经过的时间
Not able print the time elapse for function by using the decorator
我创建了一个装饰器,当 运行 程序给出 0 毫秒作为给定装饰器的输出时,它会计算一个函数所用的时间,并且在调试工具中它显示开始/结束时间已计算但未计算能够打印(结束 - 开始),如代码和输出所示。
我的代码:
import time
def time_cal(func):
def wrapper(*args, **kwargs):
start=time.time()
result = func(*args, **kwargs)
end= time.time()
print(func.__name__+ ' took ' + str((end-start)*1000) + ' milli seconds')
return result
return wrapper
a = (1,2,3,5,3,4,4)
b= [1,2,46,565,464]
c= {'num1': '1','num2' : '2', 'num3' : '3'}
en=[]
@time_cal
def evevn_num(i):
for i in b:
if i%2==0:
en.append(i)
else:
print("none are present")
return print(en)
@time_cal
def list_num(f,s,t):
print('number one',f)
print('number two', s)
print('number three', t)
kwargs = {"t": "Three", "s": "Two", "fs": "One"}
evevn_num(b)
list_num(1,2,3)
输出:
none are present
none are present
[2, 46, 464]
evevn_num took 0.0 milli seconds
number one 1
number two 2
number three 3
list_num took 0.0 milli seconds
Process finished with exit code 0
请根据代码帮我解决时间计算问题
您的代码按预期工作,只是完成功能的速度只需要 .0013666152954102 seconds
即可完成。
为了测试,请将 time.sleep(1)
添加到装饰器或尝试使用更复杂的函数。
def time_cal(func):
def wrapper(*args, **kwargs):
start=time.time()
time.sleep(1)
result = func(*args, **kwargs)
end= time.time()
print(func.__name__+ ' took ' + str((end-start)*1000) + ' milli seconds')
return result
return wrapper
结果:
none are present
none are present
even_num took 1009.1550350189209 milli seconds
number one 1
number two 2
number three 3
list_num took 1000.5834102630615 milli seconds
我创建了一个装饰器,当 运行 程序给出 0 毫秒作为给定装饰器的输出时,它会计算一个函数所用的时间,并且在调试工具中它显示开始/结束时间已计算但未计算能够打印(结束 - 开始),如代码和输出所示。
我的代码:
import time
def time_cal(func):
def wrapper(*args, **kwargs):
start=time.time()
result = func(*args, **kwargs)
end= time.time()
print(func.__name__+ ' took ' + str((end-start)*1000) + ' milli seconds')
return result
return wrapper
a = (1,2,3,5,3,4,4)
b= [1,2,46,565,464]
c= {'num1': '1','num2' : '2', 'num3' : '3'}
en=[]
@time_cal
def evevn_num(i):
for i in b:
if i%2==0:
en.append(i)
else:
print("none are present")
return print(en)
@time_cal
def list_num(f,s,t):
print('number one',f)
print('number two', s)
print('number three', t)
kwargs = {"t": "Three", "s": "Two", "fs": "One"}
evevn_num(b)
list_num(1,2,3)
输出:
none are present
none are present
[2, 46, 464]
evevn_num took 0.0 milli seconds
number one 1
number two 2
number three 3
list_num took 0.0 milli seconds
Process finished with exit code 0
请根据代码帮我解决时间计算问题
您的代码按预期工作,只是完成功能的速度只需要 .0013666152954102 seconds
即可完成。
为了测试,请将 time.sleep(1)
添加到装饰器或尝试使用更复杂的函数。
def time_cal(func):
def wrapper(*args, **kwargs):
start=time.time()
time.sleep(1)
result = func(*args, **kwargs)
end= time.time()
print(func.__name__+ ' took ' + str((end-start)*1000) + ' milli seconds')
return result
return wrapper
结果:
none are present
none are present
even_num took 1009.1550350189209 milli seconds
number one 1
number two 2
number three 3
list_num took 1000.5834102630615 milli seconds