Whilst there seems to be consent about superior memory efficiency, functionality and convenience of Numpy arrays about Python arrays, I dare questioning higher writing speeds.
In the following example I write random numbers to a pre-initialized Python and Numpy array of increasing size:
import numpy as np
import time as tm
import random
import matplotlib.pyplot as plt
array_sizes = [1000,5000,10000,50000,100000,500000,1000000,5000000]
time = []
time_np = []
for size in array_sizes:
print('Array size:', size)
# array initilization
array = [None]*size
array_np = np.array([None]*size)
tic = tm.monotonic()
for i in range(size):
array[i] = random.random()
toc = tm.monotonic()
print('PY:',toc-tic)
time.append(toc-tic)
tic = tm.monotonic()
for i in range(size):
array_np[i] = random.random()
toc = tm.monotonic()
print('NP:',toc-tic)
time_np.append(toc-tic)
For plotting add this code:
x = array_sizes
plt.figure().add_subplot(1, 1, 1).set_xscale('log')
plt.plot(x,time, color='red', label='Python array', marker='o')
plt.plot(x,time_np, color='blue', label='Numpy array', marker='^')
plt.title('Writing random numbers\nto 1D Python and Numpy array', fontweight='bold', fontsize='14')
plt.xlabel('array size')
plt.ylabel('writing time / s')
plt.legend()
plt.show()
These time measurements show the writing time to the Numpy array to be more than doubled.
What is the reason for this?