如何在Python中使用零初始化整数array.array对象

时间:2016-05-21 11:11:07

标签: python arrays initialization

具有相似标题的问题涉及Python列表或NumPy。这是关于标准Python库的array.array类部分,请参阅https://docs.python.org/2/library/array.html

我提出的禁区方法(对于整数类型)是使用带有/ dev / zero的array.fromfile。这是

  • 比array.array(' L',[0] *大小)快27倍,暂时需要的内存是最终阵列的两倍以上,
  • 比arrar.array快了4.7倍(' L',[0])* size
  • 比使用自定义可迭代对象快200多倍(以避免创建大型临时列表)。

但是,某些平台上可能无法使用/ dev / zero。如果没有NumPy,非标准模块或我自己的c-extension,有没有更好的方法呢?

示威者代码:

import array
import sys
import time

size = 100 * 1000**2
test = sys.argv[1]

class ZeroIterable:
    def __init__(self, size):
        self.size = size
        self.next_index = 0
    def next(self):
        if self.next_index == self.size:
            raise StopIteration
        self.next_index = self.next_index + 1
        return 0
    def __iter__(self):
        return self

t = time.time()
if test == 'Z':
    myarray = array.array('L')
    f = open('/dev/zero', 'rb')
    myarray.fromfile(f, size)
    f.close()
elif test == 'L':
    myarray = array.array('L', [0] * size)
elif test == 'S':
    myarray = array.array('L', [0]) * size
elif test == 'I':
    myarray = array.array('L', ZeroIterable(size))     
print time.time() - t

1 个答案:

答案 0 :(得分:1)

已更新为Python 3,并添加了'B'方法:

import array
import sys
import time

size = 100 * 1000**2
test = sys.argv[1]

class ZeroIterable:
    def __init__(self, size):
        self.size = size
        self.next_index = 0
    def __next__(self):
        if self.next_index == self.size:
            raise StopIteration
        self.next_index = self.next_index + 1
        return 0
    def __iter__(self):
        return self

t = time.time()
if test == 'Z':
    myarray = array.array('L')
    f = open('/dev/zero', 'rb')
    myarray.fromfile(f, size)
    f.close()
elif test == 'L':
    myarray = array.array('L', [0] * size)
elif test == 'S':
    myarray = array.array('L', [0]) * size
elif test == 'I':
    myarray = array.array('L', ZeroIterable(size))
elif test == 'B':
    myarray = array.array('L', bytes(size * 8))
print(len(myarray))
print(time.time() - t)

'S'方法(array.array('L', [0]) * size)获胜:

$ python3 --version
Python 3.7.3
$ python3 z.py Z
100000000
1.1691830158233643
$ python3 z.py L
100000000
2.712920665740967
$ python3 z.py S
100000000
0.6910817623138428
$ python3 z.py B
100000000
0.9187061786651611
$ python3 z.py I
100000000
62.862160444259644