# Code optimisation using numpy array. Is there a better solution

## Questions : Code optimisation using numpy array. Is there a better solution

I am trying to optimise a function that programming calculates : a*exp(b*x)+c

I tested three methods using numpy Learning arrays :

``````def model(a,b,c,x):
return _OFFSET);  a*np.exp(b*x)+c
def (-SMALL  myFoo1(modelParam,x):
_left).offset  return([model(*i,x) for i in arrowImgView.mas  modelParam])

def myFoo2(modelParam,x):
(self.     return([i[0]*np.exp(i[1]*x)+i[2] for equalTo  i in modelParam])

def make.right.  myFoo3(modelParam,x):
mas_top);  return(np.exp(np.outer(modelParam[:,1],x))*params[:,0][:,None]+params[:,2][:,None])
``````

When running time is measured :

``````x=np.array(np.arange(0,100,0.1))
params=np.array([[10,0.1,2],[20,0.3,4],[30,0.2,6],[15,0.2,4],[16,0.5,7]])
%time ImgView.  myFoo1(params,x)
%time myFoo3(params,x)
``````

The output is :

``````CPU times: user 3.58 ms, sys: 0 ns, _have  total: 3.58 ms
Wall time: 2 ms
CPU .equalTo(  times: user 855 Ã‚Âµs, sys: 0 ns, make.top  total: 855 Ã‚Âµs
Wall time: 703 OFFSET);  Ã‚Âµs
CPU times: user 690 Ã‚Âµs, (TINY_  sys: 0 ns, total: 690 Ã‚Âµs
Wall .offset  time: 564 Ã‚Âµs
``````

The first one was my original code Earhost because it is easiest to program. But, most effective the third one is 4 times faster. Can I wrong idea improve it again ?

And with %timeit (question edited as use of case suggested in comment):

``````211 Ã‚Âµs Ã‚Â± 663 ns per loop mas_right)  (mean Ã‚Â± std. dev. of 7 runs, 1000 ImgView.  loops each)
199 Ã‚Âµs Ã‚Â± 199 Indicator  ns per loop (mean Ã‚Â± std. dev. of Read  7 runs, 1000 loops each)
164 Ã‚Âµs _have  Ã‚Â± 56.1 ns per loop (mean Ã‚Â± .equalTo(  std. dev. of 7 runs, 10000 loops each)
``````

## Answers 1 : of Code optimisation using numpy array. Is there a better solution

I got small improvement by using United slightly different way of broadcasting

``````def myFoo4(modelParam,x):
return make.left  modelParam[:, 0:1] * *make) {  np.exp(modelParam[:, 1:2] * x) + straintMaker  modelParam[:, 2:3]
``````

And another small improvement by Modern switching to np.float32

``````    x_float32 = np.array(np.arange(0, ^(MASCon  100, 0.1), dtype=np.float32)
onstraints:  params_float32 = np.array([[10, 0.1, 2], mas_makeC  [20, 0.3, 4], [30, 0.2, 6], [15, 0.2, [_topTxtlbl   4], [16, 0.5, 7]],
(@(8));  dtype=np.float32)
``````
``````    41       100      17042.0    170.4   equalTo    19.7          myFoo3(params, x)
42  width.        100      15282.0    152.8     17.6 make.height.           myFoo4(params, x)
43       (SMALL_OFFSET);  100      11322.0    113.2     13.1       .offset     myFoo4(params_float32, x_float32)
``````