Home > OS >  Are numpy arrays faster than lists? [closed]
Are numpy arrays faster than lists? [closed]

Time:10-08

I am new to using python and numpy arrays.While i was going through the notes online,saw a mention about how ndarray's are faster than lists..

"NumPy arrays are stored at one continuous place in memory unlike lists, so processes can access and manipulate them very efficiently."

So i tried using timeit on a map which sqr roots each element in the list

from timeit import timeit
timeit(stmt='import math;a_list = list(range(1,100000));list(map(math.sqrt,a_list))',number=1000)

8.955352897006378

and timeit on a map which sqr roots each element in a numpy

timeit(stmt='import numpy as np;import math;np_array=np.array(range(1,100000));list(map(math.sqrt,np_array))',number=1000)

24.691162549999717

doesn't make sense,lists seem faster

CodePudding user response:

introducing numpy in your code means introduce another kind of thinking at problems.

numpy in general are more expensive in the creation phase but blazing fast for vectorial computation.

I think this is more or less what you are searching for

timeit(stmt='list(map(math.sqrt,a_list))', setup='import math; a_list = list(range(1,100000))',number=1000)
#8.64

vs:

timeit(stmt='numpy.sqrt(a_list)', setup='import numpy; a_list = numpy.arange(100000)',number=1000)
#0.4

These are the results of timeit, only applied on the computation part. I mean, computing the sqrt and ignoring time to import the libraries.

  • Related