help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: I'll try again: oct and arrays


From: Jaroslav Hajek
Subject: Re: I'll try again: oct and arrays
Date: Thu, 30 Dec 2010 14:35:48 +0100

On Wed, Dec 29, 2010 at 2:34 PM, Jesper Schmidt Hansen
<address@hidden> wrote:
> Hi again,
>
> Terribly sorry about my last submission - apparently I pushed a button
> somewhere and send an incomplete message.
>
> I have been wondering about this for some time now. It seems that if I
> access array elements via the operator ( ) in an OCT file, the
> function performs poorly compared to if I access the elements in a
> simple double array directly with [ ]. For example, if I wish to sum
> the elements in a two dimensional array I could do something like
> this:
>
> ------------------------------------------------
>
> DEFUN_DLD(octsum, argv, , "Some help text"){
>  octave_value_list retval;
>
>  // Checking inputs etc
>
>  Matrix A( argv(0).matrix_value() );
>  size_t nr = A.rows(); size_t nc = A.cols();
>
>  double sum = 0.0;
>  for ( size_t i=0; i<nr; i++ )
>   for ( size_t j=0; j<nc; j++ ) sum += A(i,j);
>
>  retval.append(octave_value(sum));
>
>  return retval;
> }
> ---------------------------------------------------
>
> I can code up the same function, but in a MEX file called mxsum. I
> will leave out the function definition since the algorithm is so
> straightforward.
>
> Now, timing the two functions I get
>
>>> A = rand(1000,1000); tic, octsum(A); toc, tic; mxsum(A); toc
>    Elapsed time is 0.0607549 seconds.
>    Elapsed time is 0.0266319 seconds.
>
> I think the difference is due to the fact that there exists an
> overhead using the () operator (not inlined by the compiler I guess),
> which is not there when you access the variable elements directly. Is
> this correct? If so, how to overcome this overhead without first
> copying everything to a second simple double array?
>

If you don't need to modify the Matrix object, declare it with const,
that avoids a copy. Unfortunately C++ is not otherwise able to
distinguish read-only from read-write use of the () operator.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]