由于大家都推荐timeit,所以这里是结果和随附的代码。
我用于测试的代码如下:
import timeit
import matplotlib.pyplot as plt
import csv
index_element_1=0
index_element_2=2
def create_csv(num_records):
'''Creates a test CSV'''
a=open('test.csv','wb')
a.write("10,20,30,40,50\n"*num_records)
a.close()
def read_csv(filename):
'''Returns iterator'''
cr = csv.reader(open(filename,"rb"))
return cr
def convert_to_list_method():
global csv_iterator
csv_list=list(csv_iterator)
length_list=len(csv_list)
x=[None]*length_list
y=[None]*length_list
for i in range(0,length_list):
x[i]=csv_list[index_element_1]
y[i]=csv_list[index_element_2]
return [x,y]
def iterate_and_append_method():
global csv_iterator
x=[]
y=[]
for row in csv_iterator:
x.append(row[index_element_1])
y.append(row[index_element_2])
return [x,y]
CSV_SIZE=range(10000,1010000,10000)
time_convert_to_list=[0]*len(CSV_SIZE)
time_iterate=[0]*len(CSV_SIZE)
count=0
for csv_size in CSV_SIZE:
create_csv(csv_size)
global csv_iterator
csv_iterator=read_csv('test.csv')
time_convert_to_list[count]=timeit.timeit("convert_to_list_method()", setup="from __main__ import *",number=1)
csv_iterator=read_csv('test.csv')
time_iterate[count]=timeit.timeit("iterate_and_append_method()", setup="from __main__ import *",number=1)
count=count+1
plt.xlabel('CSV Size')
plt.ylabel('Time (s)')
plt.plot(CSV_SIZE,time_convert_to_list,label='Convert to List')
plt.plot(CSV_SIZE,time_iterate,label='Iterate')
plt.legend()
plt.show()
结果变化不大。我认为所有的评论都是正确的。这并没有太大的区别。
注意:我在 timeit 中只使用了每个函数的 1 次迭代,因为 o/w 必须重新创建迭代器,因为它被上一次迭代消耗了!