python list与numpy数组效率对比

作者:强殖装甲凯普 时间:2023-08-18 22:49:39 

前言

因为经常一训练就是很多次迭代,所以找到效率比较高的操作能大大缩短运行时间,但这方面资料不足,所以自己记录总结一下,有需要再补充

索引效率与内存占用比较

有时候我需要一个数组,然后可能会频繁从中索引数据,那么我选择list还是numpy array呢,这里做了一个简单的实验进行比较,环境python 3.6

import random
import numpy as np
import time
import sys
# import matplotlib
# matplotlib.use('agg')
import matplotlib.pyplot as plt
from collections import deque

start = time.time()
length = []

list_size = []
array_size = []
deque_size = []

list_time = []
array_time = []
deque_time = []

for l in range(5, 15000, 5):
   print(l)
   length.append(l)
   a = [1] * l
   b = np.array(a)
   c = deque(maxlen=l)
   for i in range(l):
       c.append(1)

# print('list的size为:{}'.format(sys.getsizeof(a)))
   # print('array的size为:{}'.format(sys.getsizeof(b)))
   # print('deque的size为:{}'.format(sys.getsizeof(c)))
   list_size.append(sys.getsizeof(a))
   array_size.append(sys.getsizeof(b))
   deque_size.append(sys.getsizeof(c))

for i in range(3):
       if i == 0:
           tmp = a
           name = 'list'
       elif i == 1:
           tmp = b
           name = 'array'
       else:
           tmp = c
           name = 'deque'

s = time.time()
       for j in range(1000000):
           x = tmp[random.randint(0, len(a)-1)]
       duration = time.time() - s

if name == 'list':
           list_time.append(duration)
       elif name == 'array':
           array_time.append(duration)
       else:
           deque_time.append(duration)

duration = time.time() - start
time_list = [0, 0, 0]
time_list[0] = duration // 3600
time_list[1] = (duration % 3600) // 60
time_list[2] = round(duration % 60, 2)
print('用时:' + str(time_list[0]) + ' 时 ' + str(time_list[1]) + '分' + str(time_list[2]) + '秒')

fig = plt.figure()

ax1 = fig.add_subplot(211)
ax1.plot(length, list_size, label='list')
ax1.plot(length, array_size, label='array')
ax1.plot(length, deque_size, label='deque')
plt.xlabel('length')
plt.ylabel('size')
plt.legend()

ax2 = fig.add_subplot(212)
ax2.plot(length, list_time, label='list')
ax2.plot(length, array_time, label='array')
ax2.plot(length, deque_time, label='deque')
plt.xlabel('length')
plt.ylabel('time')
plt.legend()

plt.show()

对不同大小的list,numpy array和deque进行一百万次的索引,结果为

python list与numpy数组效率对比

可以看出,numpy array对内存的优化很好,长度越大,其相比list和deque占用内存越少。

list比deque稍微好一点。因此如果对内存占用敏感,选择优先级:numpy array>>list>deque

时间上,在15000以下这个长度,list基本都最快。其中

  • 长度<1000左右时,deque跟list差不多,选择优先级:list&asymp; \approx&asymp;deque>numpy array;

  • 长度<9000左右,选择优先级:list>deque>numpy array;

  • 长度>9000左右,选择优先级:list>numpy array>deque;

不过时间上的差距都不大,几乎可以忽略,差距主要体现在内存占用上。因此如果对内存不敏感,list是最好选择。

整个实验使用i7-9700,耗时2.0 时 36.0分20.27秒,如果有人愿意尝试更大的量级,更小的间隔,欢迎告知我结果。

添加效率比较

numpy的数组没有动态改变大小的功能,因此这里numpy数据只是对其进行赋值。

import numpy as np
import time
from collections import deque

l = 10000000
a = []
b = np.zeros(l)
c = deque(maxlen=l)
for i in range(3):
   if i == 0:
       tmp = a
       name = 'list'
   elif i == 1:
       tmp = b
       name = 'array'
   else:
       tmp = c
       name = 'deque'

start = time.time()
   if name == 'array':
       for j in range(l):
           tmp[j] = 1
   else:
       for j in range(l):
           tmp.append(1)
   duration = time.time() - start
   time_list = [0, 0, 0]
   time_list[0] = duration // 3600
   time_list[1] = (duration % 3600) // 60
   time_list[2] = round(duration % 60, 2)
   print(name + '用时:' + str(time_list[0]) + ' 时 ' + str(time_list[1]) + '分' + str(time_list[2]) + '秒')

结果为:

list用时:0.0 时 0.0分1.0秒
array用时:0.0 时 0.0分1.14秒
deque用时:0.0 时 0.0分0.99秒

可以看出,只有在非常大的量级上才会出现区别,numpy array的赋值是最慢的,list和deque差不多

但平时这些差距几乎可以忽略。

来源:https://blog.csdn.net/qq_38163755/article/details/109392728

标签:python,list,numpy数组,效率
0
投稿

猜你喜欢

  • Python图像处理之图像的缩放、旋转与翻转实现方法示例

    2023-03-09 11:25:20
  • Python调用钉钉自定义机器人的实现

    2023-08-29 20:08:55
  • php简单生成一组与多组随机字符串的方法

    2023-10-04 02:10:09
  • MySQL优化教程之超大分页查询

    2024-01-28 08:30:57
  • OpenCV哈里斯(Harris)角点检测的实现

    2022-10-07 01:41:26
  • python算法加密 pyarmor与docker

    2023-02-15 02:17:32
  • 批处理与python代码混合编程的方法

    2023-08-26 10:45:32
  • Python创建xml的方法

    2021-11-25 05:59:44
  • python四个坐标点对图片区域最小外接矩形进行裁剪

    2022-01-18 02:18:09
  • 关于Oracle listener日志解析利器的使用方法

    2024-01-13 21:36:59
  • ASP隐藏真实文件的下载功能实现代码

    2011-04-14 11:12:00
  • 解决json中ensure_ascii=False的问题

    2023-01-04 10:49:11
  • Python opencv图像基本操作学习之灰度图转换

    2023-02-17 09:04:43
  • Python字符串的拆分与连接详解

    2021-12-05 19:43:49
  • Python中关键字global和nonlocal的区别详解

    2023-08-02 16:42:33
  • Python数学建模学习模拟退火算法多变量函数优化示例解析

    2021-05-07 09:36:37
  • Python中使用md5sum检查目录中相同文件代码分享

    2022-10-31 19:57:59
  • Python3爬虫发送请求的知识点实例

    2023-04-17 19:16:32
  • MySQL系列之九 mysql查询缓存及索引

    2024-01-22 12:46:10
  • MySQL之主键索引排序失效问题

    2024-01-19 10:38:53
  • asp之家 网络编程 m.aspxhome.com