Python | List和Deque的速度对比

结论:

        操作队尾元素时,速度差可忽略不计;

        操作队头元素时,Deque远快于List

from collections import deque
from time import time

def test(num, struct, fun):
    sta = time()
    for _ in range(num):
        fun(struct)
    end = time()
    print("time cost: ", end - sta)

1 队尾插入元素---速度对比

num = int(1e7)
struct = list()
fun = lambda struct: struct.append(1)
test(num, struct, fun)

time cost:  0.7700014114379883
num = int(1e7)
struct = deque()
fun = lambda struct: struct.append(1)
test(num, struct, fun)

time cost:  0.6693985462188721

2 队尾弹出元素---速度对比

num = int(1e7)
struct = list(i for i in range(num))
fun = lambda struct: struct.pop()
test(num, struct, fun)

time cost:  0.8014125823974609
num = int(1e7)
struct = deque(i for i in range(num))
fun = lambda struct: struct.pop()
test(num, struct, fun)

time cost:  0.6997454166412354

3 队头插入元素---速度对比

num = int(1e5)
struct = list()
fun = lambda struct: struct.insert(0, 1)
test(num, struct, fun)

time cost:  1.4022290706634521
num = int(1e5)
struct = deque()
fun = lambda struct: struct.appendleft(1)
test(num, struct, fun)

time cost:  0.012262105941772461
num = int(1e5)
struct = deque()
fun = lambda struct: struct.insert(0, 1)
test(num, struct, fun)

time cost:  0.00999760627746582

4 队头弹出元素---速度对比

num = int(1e5)
struct = list(i for i in range(num))
fun = lambda struct: struct.pop(0)
test(num, struct, fun)

time cost:  9.153056383132935
num = int(1e5)
struct = deque(i for i in range(num))
fun = lambda struct: struct.popleft()
test(num, struct, fun)

time cost:  0.007311344146728516

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值