本帖最后由 歌者文明清理员 于 2023-3-25 16:07 编辑
2 效率高,因为:
# -*- coding:utf-8 -*-
from time import perf_counter_ns
def check_time(func):
def new(*args, **kwargs):
start = perf_counter_ns()
func(*args, **kwargs)
end = perf_counter_ns()
diff = end - start
return diff
return new
@check_time
def listfor():
list1 = [["牛奶", 5], ["面包", 20], ["水", 7]]
f = "水"
for i in list1:
if i[0] == f:
print(i[1], "元")
break
else:
print("未查寻到该物品!")
@check_time
def dict():
dict1 = {"牛奶": 5, "面包": 20, "水": 7}
f = "水"
try:
print(dict1[f], "元")
except:
print("未查寻到该物品!")
def print(*args, **kwargs):
pass
t1 = 0
t2 = 0
count = int(input('测试次数:'))
for i in range(count):
t1 += listfor()
for i in range(count):
t2 += dict()
del print
a1 = t1 / count
a2 = t2 / count
print('Unit: 纳秒')
print('list+for:')
print(' - total ', t1)
print(' - average', a1)
print('dict:')
print(' - total ', t2)
print(' - average', a2)
自己试试
我的结果是:测试次数:1000000
Unit: 纳秒
list+for:
- total 357286400
- average 357.2864
dict:
- total 246054500
- average 246.0545
@isdkz @liuhongrun2022 @sfqxx @Mike_python小 @wp231957 @zhangjinxuan |