import numpy as np import time import matplotlib.pyplot as plt def test1(n): lst=[] for i in range(n): lst+=[i] return lst def test2(n): lst=[] for i in range(n): lst.append(i) return lst def test3(n): return [i for i in range(n)] def test4(n): return list(range(n)) def test5(n): return list(np.arange(n)) def test1_time(n): t1=time.time() test1(n) t2=time.time() return t2-t1 def test2_time(n): t1=time.time() test2(n) t2=time.time() return t2-t1 def test3_time(n): t1=time.time() test3(n) t2=time.time() return t2-t1 def test4_time(n): t1=time.time() test4(n) t2=time.time() return t2-t1 def test5_time(n): t1=time.time() test5(n) t2=time.time() return t2-t1 x=list(range(10000,500000,10000)) y1=[test1_time(i) for i in x] y2=[test2_time(i) for i in x] y3=[test3_time(i) for i in x] y4=[test4_time(i) for i in x] y5=[test5_time(i) for i in x] plt.plot(x,y1,color='red') plt.plot(x,y2,color='green') plt.plot(x,y3,color='yellow') plt.plot(x,y4,color='blue') plt.plot(x,y5,color='black') plt.legend(["test1", "test2","test3","test4","test5"]) plt.show()
从构造的时间上来看,应该首先用list(range(n))来进行,其次用numpy.arange(n)。其他的可以不考虑推荐了。