2

I was performing some code timing of cells in jupyter notebook where I was writing to segments of a numpy array and found that breaking up the code produces a different processing time, compared to original combined code.

The folowing is a minimal example code. First setting up some values:

import numpy as np
V=10000
K=1000
zrs=np.random.random(V)

Then timing full code:

%%timeit
a=np.zeros(V*K)
for n in range(0,K):
    a[n*V:(n+1)*V]=zrs

this returns: 45.6 ms ± 2.82 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

However, if I run the code in separate cells, I get:

%%timeit
a=np.zeros(V*K)

307 µs ± 2.33 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

and, first declaring 'a':

a=np.zeros(V*K)

then running timeit on the second part of the code:

%%timeit
for n in range(0,K):
    a[n*V:(n+1)*V]=zrs

9.52 ms ± 214 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

To conclude running complete code i get ~46ms and running the code in separate segments I get ~10ms!

Why? I am confused! What can I expect when running the code?

Help appreciated :)

Python 3.6.3, jupyter notebook 5.0.0

Mecgrad
  • 64
  • 5

0 Answers0