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

2023-11-24

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

我想出的快速方法(对于整数类型)是将 array.fromfile 与 /dev/zero 一起使用。这是

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

但是,/dev/zero 在某些平台上可能不可用。有没有更好的方法可以在没有 NumPy、非标准模块或我自己的 c 扩展的情况下做到这一点?

演示代码:

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

更新到 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) wins:

$ 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Python 中用零初始化整数 array.array 对象 的相关文章

随机推荐