[英]How to initialise an integer array.array object with zeros in Python
标题相似的问题是关于 Python 列表或 NumPy。 这是关于标准 Python 库的 array.array 类部分,请参阅https://docs.python.org/2/library/array.html
我想出的禁食方法(对于整数类型)是将 array.fromfile 与 /dev/zero 一起使用。 这是
但是,/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
)获胜:
$ 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.