Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I optimize array access in python?

running time python my.py gets me 1.35s with the code below. Writing import py_compile, py_compile.compile('my.py', optimize=2) and running the file using time python __pycache__/my.cpython-310.opt-2.pyc gets me the same speed or slower. What can I do to speed this up?

import array
a = array.array('B')
for i in range(0, 1024*1024*10):
    a.append(i & 255)
print(str(len(a)))

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here are some possible options:

import timeit


def array():
    import array
    a = array.array('B')
    for i in range(0, 1024 * 1024 * 10):
        a.append(i & 255)
    print(str(len(a)))


def list_comprehension():
    a = [i & 255 for i in range(0, 1024 * 1024 * 10)]
    print(str(len(a)))


def numpy_array():
    import numpy as np
    a = np.arange(0, 1024 * 1024 * 10, dtype=np.uint8) & 255
    print(str(len(a)))


def numpy_array_repeat():
    import numpy as np
    a = np.tile(np.arange(0, 256, dtype=np.uint8), 4 * 1024 * 10 )
    print(str(len(a)))


print("array", timeit.timeit(array, number=5))
print("list_comprehension", timeit.timeit(list_comprehension, number=5))
print("numpy_array", timeit.timeit(numpy_array, number=5))
print("numpy_array_repeat", timeit.timeit(numpy_array_repeat, number=5))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading