[Python] Why numpy.array so slow when editing the data inside?

Discussão em 'Python' iniciado por Stack, Dezembro 21, 2024.

  1. Stack

    Stack Membro Participativo

    I wrote an algorithm that uses a long list. Since numpy.array should perform better in dealing with long data, I wrote another version using numpy.array.

    list version:

    import math
    def PrimeTable(n:int) -> list[int]:
    nb2m1 = n//2 - 1
    l = [True]*nb2m1
    for i in range(1,(math.isqrt(n)+1)//2):
    if l[i-1]:
    for j in range(i*3,nb2m1,i*2+1):
    l[j] = False
    return [2] + [i for i,v in zip(range(3,n,2), l) if v]


    array version:

    import math, numpy
    def PrimeTable2(n:int) -> list[int]:
    nb2m1 = n//2 - 1
    l = numpy.full(nb2m1, True)
    for i in range(1,(math.isqrt(n)+1)//2):
    if l[i-1]:
    for j in range(i*3,nb2m1,i*2+1):
    l[j] = False
    return [2] + [i for i,v in zip(range(3,n,2), l) if v]


    It turns out that numpy.array version is 1x slower than list version. The graph:[​IMG]where y0 is PrimeTable and y1 is PrimeTable2

    Why is numpy.array so slow, and how can I improve it?

    Continue reading...

Compartilhe esta Página