I have following piece of code with if statement within a function. When I run it would take long time and it is a way to rewrite if condition or a way to speed up this sample code?
import numpy as np
def func(S, R, H):
ST = S * R
if ST <= - H:
result = - H
elif ST >= - H and ST < 0:
result = ST
else:
result = min(ST, H)
return result
y=[]
t1= time()
for x in np.arange(0, 10000, 0.001):
y.append(func(3, 5, x))
t2 = time()
print("time with numpy arange:", t2-t1)
time taken to run the code:
10 s
This is reproduced sample of real code, and in the real code ST becomes both negative and positive value, we may keep conditions but changing if statement to something else may help perfom task faster!