It's misguiding to say that a code with arrays runs faster. In general, when people speak about code going faster with Numpy arrays, they point out the benefit of vectorizing the code which can then run faster with Numpy performant implementation of functions for array operations and manipulation. I wrote a code that compares the second code you provided (I slightly modified it to save values on a list in order to compare the results) and I compared it to a vectorized version. You can see that this leads to a significant increase in time and the results given by the two methods are equal:
from time import time
import numpy as np
# We use a list and apply the operation for all elemnt in it => return a list
def stresslist(STEEL_E_MODULE, strain_in_rebars_list, STEEL_STRENGTH):
stress_list = []
for strain_in_rebars in strain_in_rebars_list:
STRESS = STEEL_E_MODULE * strain_in_rebars
if STRESS <= - STEEL_STRENGTH:
stress = - STEEL_STRENGTH
elif STRESS >= - STEEL_STRENGTH and STRESS < 0:
stress = STRESS
else:
stress = min(STRESS, STEEL_STRENGTH)
stress_list.append(stress)
return stress_list
# We use a numpy array and apply the operation for all elemnt in it => return a array
def stressnumpy(STEEL_E_MODULE, strain_in_rebars_array, STEEL_STRENGTH):
STRESS = STEEL_E_MODULE * strain_in_rebars_array
stress_array = np.where(
STRESS <= -STEEL_STRENGTH, -STEEL_STRENGTH,
np.where(
np.logical_and(STRESS >= -STEEL_STRENGTH, STRESS < 0), STRESS,
np.minimum(STRESS, STEEL_STRENGTH)
)
)
return stress_array
t_start = time()
x = stresslist( 2, list(np.arange(-1000,1000,0.01)), 20)
print(f'time with list: {time()-t_start}s')
t_start = time()
y = stressnumpy( 2, np.arange(-1000,1000,0.01), 20)
print(f'time with numpy: {time()-t_start}s')
print('Results are equal!' if np.allclose(y,np.array(x)) else 'Results differ!')
Output:
% python3 script.py
time with list: 0.24164390563964844s
time with numpy: 0.003011941909790039s
Results are equal!
Please do not hesitate if you have questions about the code. You can also refer to the official documentation for numpy.where, numpy.logical_and and numpy.minimum.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…