-1
import numpy as np

x = np.arange(10**5)

for i in xrange(x.size):
    foo(x[3000:40000])

and just another version of the code above

import numpy as np

x = np.arange(10**5)
slice_of_x = x[3000:40000] 
for i in xrange(x.size):
    foo(slice_of_x)

Will the second code be faster or not? I am inclined to think in terms of pointer in C (so that infact the first may be faster) but I understand python is no C.

O.k. This post Slicing a list in Python without generating a copy answers my question.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
user1318806
  • 785
  • 3
  • 9
  • 13

1 Answers1

1

Read this http://scipy-lectures.github.io/advanced/advanced_numpy/#life-of-ndarray, in particular the section Slicing with integers.

From the page [on slicing]

Everything can be represented by changing only shape, strides, and possibly adjusting the data pointer! Never makes copies of the data

So the overhead of creating a slice is small: constructing a Python object which stores a few tuples and a pointer to the data.

In your first code sample, you create the slice in the loop each time. In the second example you create the slice once. The difference will probably be negligible for most functions foo that you would choose to write.

YXD
  • 31,741
  • 15
  • 75
  • 115