首页 > 其他分享 >列表首位末尾插入删除用时比较

列表首位末尾插入删除用时比较

时间:2022-10-12 08:33:23浏览次数:51  
标签:__ timeit seconds 用时 pop 列表 range 末尾 1000

def test1():
   l = []
   for i in range(1000):
      l = l + [i]
def test2():
   l = []
   for i in range(1000):
      l.append(i)
def test3():
   l = [i for i in range(1000)]
def test4():
   l = list(range(1000))

from timeit import Timer

t1 = Timer("test1()", "from __main__ import test1")
print("concat ",t1.timeit(number=1000), "seconds")
t2 = Timer("test2()", "from __main__ import test2")
print("append ",t2.timeit(number=1000), "seconds")
t3 = Timer("test3()", "from __main__ import test3")
print("comprehension ",t3.timeit(number=1000), "seconds")
t4 = Timer("test4()", "from __main__ import test4")
print("list range ",t4.timeit(number=1000), "seconds")
# 输出
# concat  0.7357939 seconds
# append  0.03698400000000002 seconds
# comprehension  0.01672129999999994 seconds
# list range  0.007648800000000011 seconds

# ('concat ', 1.7890608310699463, 'seconds')
# ('append ', 0.13796091079711914, 'seconds')
# ('comprehension ', 0.05671119689941406, 'seconds')
# ('list range ', 0.014147043228149414, 'seconds')
x = list(range(2000000))
pop_zero = Timer("x.pop(0)","from __main__ import x")
print("pop_zero ",pop_zero.timeit(number=1000), "seconds")
x = list(range(2000000))
pop_end = Timer("x.pop()","from __main__ import x")
print("pop_end ",pop_end.timeit(number=1000), "seconds")

# pop_zero  3.7069058 seconds
# pop_end  3.4799999999890474e-05 seconds

标签:__,timeit,seconds,用时,pop,列表,range,末尾,1000
From: https://www.cnblogs.com/heris/p/16783245.html

相关文章