高效的Python阵列1亿零? [英] Efficient Python array with 100 million zeros?

查看:157
本文介绍了高效的Python阵列1亿零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是在Python初始化和访问一个大数组的元素的有效方式?

What is an efficient way to initialize and access elements of a large array in Python?

我要在Python中创建100万个条目,无符号的4字节的整数,初始化为零的数组。我想快速数组访问,$ P用连续的内存pferably $。

I want to create an array in Python with 100 million entries, unsigned 4-byte integers, initialized to zero. I want fast array access, preferably with contiguous memory.

奇怪的是, numpy的阵列似乎在进行非常缓慢。是否有替代品,我可以试试吗?

Strangely, NumPy arrays seem to be performing very slow. Are there alternatives I can try?

有是href=\"http://docs.python.org/library/array.html\"> array.array 模块

There is the array.array module, but I don't see a method to efficiently allocate a block of 100 million entries.

回应评论:


  • 我无法用一个稀疏数组。因为数组很快变得致密这将是这个算法太慢了。

  • 我知道Python是间preTED,但肯定是有办法做到快数组操作?

  • 我做了一些分析,我也得到约每秒160K数组访问(查找或更新索引的元素)与numpy的。这似乎很慢。

推荐答案

我已经做了一些分析,结果是完全有悖常理。
对于简单的数组访问操作, numpy的和array.array比原生的Python阵列

I have done some profiling, and the results are completely counterintuitive. For simple array access operations, numpy and array.array are 10x slower than native Python arrays.

请注意,对于数组访问,我做的形式操作:

Note that for array access, I am doing operations of the form:

a[i] += 1

简介:


  • [0] * 20000000

  • [0] * 20000000


  • 访问:2.3M /秒

  • 初始化:0.8S

numpy.zeros(形状=(20000000,),DTYPE = numpy.int32)

numpy.zeros(shape=(20000000,), dtype=numpy.int32)


  • 访问:160K /秒

  • 初始化:0.2S

array.array('L',[0] * 20000000)

array.array('L', [0] * 20000000)


  • 访问:175K /秒

  • 初始化:2.0S

array.array('L',(0为我的range(20000000)))

array.array('L', (0 for i in range(20000000)))


  • 访问:175K /秒,presumably,基于为其他array.array的配置文件

  • 初始化:6.7s

这篇关于高效的Python阵列1亿零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆