Question on Vector computation

For developers writing C++, Fortran, Java, code who have questions or comments to make.

Moderators: silvia, selimgunay, Moderators

Post Reply
Kazuya

Question on Vector computation

Post by Kazuya » Thu Oct 28, 2004 2:10 pm

I need to perform lots of Vector computations efficiently.
Suppose we need to compute
Vres=a*V1+b*V2+c*V3
where
Vres, V1, V2 and V3 : Vectors,
a,b,c: constants.

Which is a better code in terms of the cpu time
1) Vres=V1*a+V2*b+V3*c
or
2) for(i=0;i<Nsize;i++) Vres(i)=V1(i)*a+V1(i)*b+V1(i)*c ?

The first one includes 3*Nsize loops for multiplication
and others for addition,
while the latter one includes Nsize loop but with
the access to the vector component.

Regrads,
Kazuya

fmk
Site Admin
Posts: 5883
Joined: Fri Jun 11, 2004 2:33 pm
Location: UC Berkeley
Contact:

Post by fmk » Thu Oct 28, 2004 3:18 pm

the first involves 5 calls to the matrix constructor & 5 subsequent calls to the destructor .. lots of memory calls to the os typically kill object-oriented programs (it's why we use references wherever we can).

the second involves all those calls to the inline functions .. while not great .. probably better .. of course how good depends on how good the compiler is at inlining the function.

a third option and the best would be to use one of the vector methods.
Vres.addVector(0.0, V1, a);
Vres.addVector(1.0, V2, b);
Vres.addVector(1.0, V3, c);

Kazuya

Vector computation

Post by Kazuya » Fri Oct 29, 2004 7:58 am

I tried third option.
Although I did not measure the cpu time,
it seemed that this option was the fastest one.
Thank you

Kazuya

Vector computation

Post by Kazuya » Fri Oct 29, 2004 10:22 am

I tried third option.
Although I did not measure the cpu time,
it seemed that this option was the fastest one.
Thank you

gangwang

Re: Vector computation

Post by gangwang » Wed Nov 10, 2004 1:37 am

Frank, can you explain more why the third is the fastest? I am interested
to learn.

Post Reply