"Now we can compare the timings with and without the ```@jit``` decorator. \\\n",
"Remember that decorators change the behaviour of the function - but we do not have to change the function itself.\n",
"\n",
"In this case, Numba is a specialised package that optimises a function \"behind the scenes\".\n",
"\n",
"Note that the first call includes the optimisation / compile time. If we want to measure the time the optimised function takes, we need to discard the timing from the first call.\n"
# the following is the same as np.random.choice([-1,1]) but this cannot be optimized with Numba
x_dir=np.round(2*(np.random.randint(0,2)-0.5))
y_dir=np.round(2*(np.random.randint(0,2)-0.5))
# calculate new positions: last position + step_size * direction
new_x=x_points[-1]+step_size*x_dir
new_y=y_points[-1]+step_size*y_dir
# append to arrays
x_points.append(new_x)
y_points.append(new_y)
# calculate distance between start and end as Eucledian distance
# bit explicit as numba does not work with the one line we have used before
x_start=x_points[0]
y_start=y_points[0]
x_stop=x_points[-1]
y_stop=y_points[-1]
distance2=(x_stop-x_start)**2+(y_stop-y_start)**2
distance=np.sqrt(distance2)
returnx_points,y_points,distance
```
%% Cell type:markdown id: tags:
Now we can compare the timings with and without the ```@jit``` decorator. \
Remember that decorators change the behaviour of the function - but we do not have to change the function itself.
In this case, Numba is a specialised package that optimises a function "behind the scenes".
Note that the first call includes the optimisation / compile time. If we want to measure the time the optimised function takes, we need to discard the timing from the first call.
%% Cell type:code id: tags:
``` python
%%time
distances=[]
foriinrange(0,200):
_,_,distance=random_walk()
distances.append(distance)
```
%% Output
CPU times: user 33.4 ms, sys: 0 ns, total: 33.4 ms