遍历输出数组内容
from timeit import default_timer as timer
import re
import csv
list=[1,2,3,4,5]
#写法1
tic = timer()
it = iter(list)
print (next(it))
print (next(it))
print (next(it))
print (next(it))
print (next(it))
toc = timer()
t1=(toc - tic)*1000
#写法2
tic = timer()
it = iter(list)
for x in it:
print(x)
toc = timer()
t2=(toc - tic)*1000
#写法3
tic = timer()
for x in list:
print(x)
toc = timer()
t3=(toc - tic)*1000
#输出结果到文件
with open('./test.csv', 'a+', newline='') as f:
write = csv.writer(f, dialect=('excel'))
write.writerow([t1,t2,t3])
输出结果
test.csv
数据(输出结果)(单位:ms):
写法1 | 写法2 | 写法3 | 最慢 | 最快 |
---|---|---|---|---|
0.7239 | 0.5169 | 0.6416 | 写法1 | 写法2 |
1.2289 | 0.1798 | 0.1234 | 写法1 | 写法3 |
0.784 | 0.5699 | 0.2963 | 写法1 | 写法3 |
1.2771 | 0.9657 | 0.1996 | 写法1 | 写法3 |
0.7761 | 0.3015 | 0.1215 | 写法1 | 写法3 |
1.4325 | 0.1925 | 0.2194 | 写法1 | 写法2 |
1.0676 | 0.5579 | 0.1247 | 写法1 | 写法3 |
0.5855 | 0.557 | 0.4559 | 写法1 | 写法3 |
1.2121 | 0.5516 | 0.1104 | 写法1 | 写法3 |
0.8683 | 0.2364 | 0.3352 | 写法1 | 写法2 |
0.5498 | 0.5194 | 0.2774 | 写法1 | 写法3 |
0.7694 | 0.6182 | 0.3232 | 写法1 | 写法3 |
1.8129 | 0.4272 | 0.19 | 写法1 | 写法3 |
1.2881 | 0.417 | 0.1472 | 写法1 | 写法3 |
1.111 | 0.5601 | 0.1247 | 写法1 | 写法3 |
1.2219 | 0.6723 | 0.4791 | 写法1 | 写法3 |
1.2496 | 0.9729 | 0.4479 | 写法1 | 写法3 |
1.0822 | 0.3603 | 0.1768 | 写法1 | 写法3 |
1.1737 | 0.8287 | 0.3181 | 写法1 | 写法3 |
0.9987 | 0.7095 | 0.4038 | 写法1 | 写法3 |
结论:在大多数情况下,使用iter
和next
搭配最慢,直接使用for
循环遍历最快。
发表您的看法