[Numpy-discussion] Zeroing an existing array
perry at stsci.edu
Thu May 15 06:16:10 EDT 2003
Andrew P. Lentvorski, Jr. wrote:
> On Wed, 14 May 2003, Perry Greenfield wrote:
> > > >>> import numarray
> > > >>> a = numarray.arange(6)
> > > >>> a
> > > array([0, 1, 2, 3, 4, 5])
> > > >>> a[:] = 0.0
> > > >>> a
> > > array([0, 0, 0, 0, 0, 0])
> > >
> > Is there any reason for anything else if this does the job?
> > This is how I would recommend the action be performed.
> It depends. How does the slicing code work?
> If it iterates across the matrix indicies (requiring multiply and add
> operations to index specific memory locations), this will be much slower
> than doing a contiguous memory fill (1 add and 1 multiply per index vs.
> increment). This is not a small hit, we're talking factors of 2x, 4x, 6x.
> If the slicing code special cases "array[:] = n" to be a memory fill, then
> probably not.
Well, there are two issues the question relates to:
1) what should the user interface be for filling arrays with
a constant value. I'd argue that a slice assignment is both
sufficent and idiomatic.
2) is it efficient.
As to 2, the current implementation handles scalar assignment by
broadcasting a one-element array across the array being assigned to
(that's the simplest way to code it). That isn't the fastest implementation
when the array being assigned to is congtiguous. It could be made
faster. But frankly, it isn't very high on our list of priorities.
And I'm a little skeptical that this performance improvement is
an important one. Is your program perfromance dominated by the time
it takes to zero an array? I have trouble thinking of many realistic
problems where that would be true (not to say that there aren't any).
If someone is willing to write special code to optimize this, that
would be fine with us.
More information about the NumPy-Discussion