Why is numpy list access slower than vanilla python?

I had the impression that numpy would be faster for list operations, but the following example seems to indicate something else:

import numpy as np
import time

def ver1():
    a = [i for i in range(40)]
    b = [0 for i in range(40)]
    for i in range(1000000):
        for j in range(40):
            b[j]=a[j]

def ver2():
    a = np.array([i for i in range(40)])
    b = np.array([0 for i in range(40)])
    for i in range(1000000):
        for j in range(40):
            b[j]=a[j]

t0 = time.time()
ver1()
t1 = time.time()
ver2()
t2 = time.time()

print(t1-t0)
print(t2-t1)

Exit:

4.872278928756714
9.120521068572998

(I am running 64-bit Python 3.4.3 on Windows 7, on i7 920)

I understand that this is not the fastest way to copy a list, but I am trying to find out if I am using numpy incorrectly. Or is it that numpy is slower for this kind of operation and only more efficient in more complex operations?

EDIT:

I also tried the following, which just does a direct copy through b [:] = a, and numpy is twice as slow:

import numpy as np
import time

def ver6():
    a = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
    b = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
    for i in range(1000000):
        b[:] = a

def ver7():
    a = np.array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])
    b = np.array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])
    for i in range(1000000):
        b[:] = a

t0 = time.time()
ver6()
t1 = time.time()
ver7()
t2 = time.time()

print(t1-t0)
print(t2-t1)

Exit:

0.36202096939086914
0.6750380992889404
+4
source share
2 answers

NumPy . NumPy C- .

for j in range(40):
    b[j]=a[j]

, NumPy , , NumPy - . - NumPy, .

, C:

b[:] = a

, NumPy.

+5

, , Python C.

Python - PyObject. a b Python, b[i] = a[i] :

  • , b[i],
  • , a[i],
  • , a[i], b[i].

a b NumPy, , b[i] = a[i] :

  • Python C, a[i], . this,
  • Python C b[i], .
  • Python.

, Python, .

+1

Source: https://habr.com/ru/post/1626043/


All Articles