There are several ways to add an element to the end of a Python array, depending on whether you use the list type or the numpy ndarray type. I was wondering how much the execution speed would be different by these methods, so when Karukuda looked it up, Comparison of append to list type Only entry / 2014/10/20/110304) was found (I'm sorry if there is insufficient research). Therefore, we will investigate the execution speed of the method of adding elements to the three arrays shown in the next section by a simple experiment. The number of times elements were added was 100,000, and the time module was used for time measurement. The code used in the experiment is placed at the very end.
How to use list.append. This is a standard method built into Python, and should be a method that even beginners of Python often use.
x = []
for i in range( 10 ):
x.append( i )
How to use numpy.append.
import numpy as np
x = np.array( [] )
for i in range( 10 ):
x = np.append( x, i )
How to use numpy.hstack.
import numpy as np
x = np.array( [] )
for i in range( 10 ):
x = np.hstack( (x,i) )
Execution time (seconds) | |
---|---|
list.append | 0.0149400234222 |
numpy.append | 4.47969698906 |
numpy.hstack | 4.75327301025 |
I expected it a little, but list.append is overwhelmingly fast. And there is no speed difference between numpy.append and numpy.hstack. After all, if you know the size of the required array in advance, it seems that the correct answer is to use ndarray, otherwise use list.
import numpy as np
def stdAppend(n):
x = []
for i in range(n):
x.append(i)
return
def npAppend(n):
x = np.array( [] )
for i in range(n):
x = np.append(x,i)
return
def npHstack(n):
x = np.array( [] )
for i in range(n):
x = np.hstack( (x,i) )
return
if __name__ == '__main__':
import time
n = 100000
start = time.time()
stdAppend(n)
ttime = time.time() - start
print( "stdAppend: %s" % ttime )
start = time.time()
npAppend(n)
ttime = time.time() - start
print( "npAppend : %s" % ttime )
start = time.time()
npHstack(n)
ttime = time.time() - start
print( "npHstack : %s" % ttime )
Recommended Posts