help-gplusplus
[Top][All Lists]
Advanced

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

Re: C++ optimization help with the creation of temporaries


From: Ulrich Eckhardt
Subject: Re: C++ optimization help with the creation of temporaries
Date: Mon, 28 Mar 2005 12:39:49 +0200
User-agent: KNode/0.8.1

edA-qa mort-ora-y wrote:
> //Fast loop (0.07s)
>      pointx target;
>      for( int i=0; i < loop; i++ )
>          for( unsigned j=0; j < 3; j++ )
>          {
>              target[j] += pa[j];
>              target[j] *= ca;
>              target[j] -= pb[j] * cb;
>          }
> 
> //Slow loop (0.23s)
>      pointx target;
>      for( int i=0; i < loop; i++ )
>      {
>          target += pa;
>          target *= ca;
>          target -= pb * cb;    //most time here
>      }
> 
> In the second last line of the second item I note most of the time is 
> spent there, so I'm guessing there is a temporary created.  The multiply 
> function for a point and scalar is:
> 
>      //dim is template parameter for point size
>      point operator*(const rtype m ) const

Two things here: I personally prefer implementing binary operators where
there is no main or principal object involved as unbound function instead
of member function. That's a matter of taste though.
Secondly, the compiler will already create a temporary when just calling
this function, you should pass a reference to const point here.

>          point n( *this );
>          for( unsigned i=0; i < dim; i++ )
>              n.vals[i] *= m;
>          return n;

Ideomatic (but I don't think it's faster here) would be to use 'i!=dim' and
'++i'. Should be in any beginners introduction to iterators and for loops.

Finally, one things you could try is to apply (partial) specialisation for
this, unrolling the loop for some cases. Maybe the boost metaprogramming
library might help you in that task, but I'm no expert in that field.
 A last thing I noticed is that sometimes float is faster than double. This
strongly depends on the processor though, so never hard-wire either choice
into your program.

Uli

-- 
http://gcc.gnu.org/faq.html
http://parashift.com/c++-faq-lite/



reply via email to

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