help-octave
[Top][All Lists]

## Re: Performance optimization (allocation inside a for loop)

 From: Jaroslav Hajek Subject: Re: Performance optimization (allocation inside a for loop) Date: Thu, 2 Apr 2009 19:37:03 +0200

```On Thu, Apr 2, 2009 at 6:23 PM, John W. Eaton <address@hidden> wrote:
> On  2-Apr-2009, James Sherman Jr. wrote:
>
> | Its redundant as far as I know, but I always use it because I think it looks
> |
> | James
> |
> | On Thu, Apr 2, 2009 at 11:58 AM, Elias Assmann <
> |
> | > Rob Mahurin wrote:
> | > > octave:29> tic; n = 1e5; retval = 1:n; toc
> | > > Elapsed time is 0.000756025 seconds.
> | > > octave:30> tic; n = 1e5; retval = (1:n)(1:n); toc
> | > > Elapsed time is 0.00757694 seconds.
> | > > octave:31> tic; n = 1e5; retval = [1:n]; toc
> | > > Elapsed time is 0.0125589 seconds.
> | >
> | > Can someone explain the difference between "1:n" and "[1:n]"?  I would
> | > normally write the brackets because I find that way clearer; does this
> | > mean "1:n" is actually the "preferred" way?
>
> In Octave, an expression like 1:n creates a range object, which
> contains only the base, limit, and increment as double precision
> values, so no matter how many elements are in the range, it only takes
> a few bytes of storage (24 for the data plus some overhead for the
> internal octave_value object itself).
>

In fact there's more, IIRC, it also stores the number of elements, and
a possibly empty Matrix cache. In a 64-bit environment, it will be 24
(data) + 8 (nelem) + 2*8 (Array::slice*) + 8 (Array:rep) + 2*8
(ArrayRep)+ 8 (dim_vector)+ 2*8 (dim_vector_rep) + 2*8 (dim_vector_rep
data) = 112 bytes (with empty cache).
This could be somewhat alleviated by storing just a (possibly null)
pointer to the Matrix cache.

> If you write [1:n], you force a Matrix object with N elements to be
> created.  It will require 8*N bytes of storage, plus the overhead for
> the internal octave_value object itself.
>
> In Octave 3.2, some operations on ranges will preserve the range data
> type.  In earlier versions, nearly all operations converted range
> objects to matrix objects first.

adding/subtracting/multiplying by a scalar, to be precise. and unary
minus. This is useful for indexing. Is anyone interested in adding /
subtracting two ranges?

> If you think it looks more readable to have something surrounding the
> range expression, then I would recommend writing (1:n) instead of [1:n].
>
> Finally, range dimensions are always [1, N], so transposing a range
> will create a matrix object.  For example, try this:
>
>  x = 1:10;
>  y = x';
>  whos
>
> and note the differents in the number of bytes used.
>
> Maybe we should consider fixing that so that we could also have
> column-oriented ranges.
>

I don't see much use for that.

cheers

--
RNDr. Jaroslav Hajek
computing expert & GNU Octave developer
Aeronautical Research and Test Institute (VZLU)
Prague, Czech Republic
url: www.highegg.matfyz.cz

```