On Jun 16, 1:58*pm, kid joe <spamt...@spamtrap.invalid> wrote:
> Hi all,
>
> I know this is fairly system specific but I was hoping some people here
> with a wide experience of C implementations on different platforms could
> pass on their knowledge.
>
> If I want to perform actions on several large arrays, whats the best way
> to do that? Lets say for a silly example I have arrays a,b,c all of size n
> and I want to multiply everything in a by 2, everything in b by 3 and
> everything in c by 4.
>
> Method 1:
> for(long int i = 0; i < n; i++) {
> * a[i] *= 2;
> * b[i] *= 3;
> * c[i] *= 4;
>
> }
>
> Method 2:
> for(long int i = 0; i < n; i++)
> * a[i] *= 2;
> for(long int i = 0; i < n; i++)
> * b[i] *= 3;
> for(long int i = 0; i < n; i++)
> * c[i] *= 4;
>
> Now you could argue that Method 1 should be faster because there are less
> branching instructions, and branching is expensive. But then you could
> argue that Method 2 should be better because theres better data locality
> so better use of cache.
>
> I know people will say to profile it on my system!
But Id be interested
> in peoples thoughts on this on a variety of different hardwares.
My opinion is that these optimizations are very, very silly.
You should not perform these optimizations unless:
1. The routine does not meet performance specifications
2. The profile reveals that initialization of arrays is the bottleneck
Array initialization is linear for a 1-D array, and so it is probably
the least of your worries.
It's like buying Pirelli P3 tires for an old Volkswagen beetle.
It's costly, it's silly, and it won't make the beetle go any faster.
P.S.
You are also right about the profile. I guess that different machines
and different compilers will give different answers. And if you
change the data types you may get different answers yet again.
P.P.S.
The first rule of optimization is "DON'T DO IT."
The second rule of optimization (for experts only) is "Don't do it
*yet*."
These are serious rules. A practice of premature optimization because
you think something might go faster due to tweaky little hacks is a
very, very, very, very bad coding practice. Not only will it make the
code more expensive, it is also going to be a complete waste of time
in almost all cases.
If you want to make code go faster, the very last place you should
ever imagine going is hopping on board the good ship "tweaky hacks."
Instead, improve the algorithm. Chances are very good you can find an
algorithm in the literature that will improve the code. If you cannot
find one, consider thinking about how to improve the algorithm
yourself.
I guess you will ignore this advice, since it did not stick last
time. That's too bad.