Python列表添加元素效率测试
#!/usr/bin/env
import datetime
class adair:
def test1(n):
lst=[]
for i in range(n*10000):
lst = lst + [i]
return lst
def test2(n):
for i in range(n*10000):
lst = lst.append(i)
return lst
def test3(n):
return [i for i in range(n*10000)]
def test4(n):
return list(range(n*10000)
if __name__ == ‘__main__‘:
f=adair()
start = datetime.datetime.now()
f.test1(2)
end = datetime.datetime.now()
print(end-start)
start = datetime.datetime.now()
f.test2(2)
end=datetime.datetime.now()
print(end-start)
start=datetime.datetime.now()
f.test3(2)
end=datetime.datetime.now()
print(end-start)
start=datetime.datetime.now()
f.test4(2)
end=datetime.datetime.now()
print(end-start)
测试结果如下:
原文地址:http://blog.51cto.com/8390593/2173452
时间: 2024-10-14 19:35:02