1

I was trying to understand the assignment of values to slices of NumPy arrays. In particular, if sliced assignments are slower than 'less sliced' assignments.

Example:

a[0,:10] = 5
vs
a[0:1,:10] = 5

This inadvertently landed me on a situation where I was trying to compare

a[:,:] = a[:,:] + 1
vs
a = a + 1

I failed to understand the results

Case 1: The array creation is outside the loop

b=np.arange(100000000).reshape(-1,100).astype(np.float64)
out = []
for i in range(50):
    ti1 = time.time()
    b = b+1
    tf1 = time.time()
    tt1 = tf1 - ti1

    ti2 = time.time()
    b[:,:] = b[:,:]+1
    tf2 = time.time()
    tt2 = tf2 - ti2
    out.append((tt1,tt2))
print(len(list(filter(lambda x: x[0] > x[1], out))))

output:

22

CASE 2 : The array creation is inside the loop

out1 = []
for i in range(50):
    b=np.arange(100000000).reshape(-1,100).astype(np.float64)
    ti1 = time.time()
    b = b+1
    tf1 = time.time()
    tt1 = tf1 - ti1

    ti2 = time.time()
    b[:,:] = b[:,:]+1
    tf2 = time.time()
    tt2 = tf2 - ti2
    out1.append((tt1,tt2))
print(len(list(filter(lambda x: x[0] > x[1], out1))))

output:

0

It seems that the first time after the creation of the array, b = b + 1 necessarily takes less time than b[:,:] = b[:,:] + 1

  • Why is it so?
  • What changes after b = b + 1 and b[:,:] = b[:,:] + 1 have been run once that they both now take up the same amount of time approximately?
figs_and_nuts
  • 4,870
  • 2
  • 31
  • 56

0 Answers0