How to initialise an integer array.array object with zeros in Python

前端 未结 1 764
谎友^
谎友^ 2021-01-18 17:18

Questions with similar titles are about Python lists or NumPy. This is about the array.array class part of the standard Python library, see https://docs.python.org/2/library

相关标签:
1条回答
  • 2021-01-18 17:46

    Updated to Python 3 and added the 'B' method:

    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)
    

    The 'S' method (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
    
    0 讨论(0)
提交回复
热议问题