top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Check the following C example, why is one loop so much slower than two loops?

+1 vote
445 views

Check the following C example, why is one loop so much slower than two loops?

Suppose we have to add some values to array a1 and c1 of b1 and d1 respectively then there is big time difference in execution of both code..

const int n=100000;
for(int j=0;j<n;j++){
    a1[j] += b1[j];
    c1[j] += d1[j];
}

This loop is executed 10,000 times via another outer for loop. to speed it up, I changed the code to:

for(int j=0;j<n;j++){
    a1[j] += b1[j];
}
for(int j=0;j<n;j++){
    c1[j] += d1[j];
}

I don't think there should be any execution time difference but it is showing.

posted Mar 13, 2016 by Shivam Kumar Pandey

Looking for an answer?  Promote on:
Facebook Share Button Twitter Share Button LinkedIn Share Button
@Shivam kumar pandey,
I tried the same thing and i don't see any time difference,
But as per the C basic logic if we see this problem then i guess the code with for loop 2 times should be slower than single for loop code.
That is not a universal truth, ideally when you break one loop to the multiple loop then multiple loop should be slower (if optimization is not enabled) because for related instructions are executed twice.

But in few cases some different factor also comes into picture like SwapIn SwapOut or CacheIn CacheOut which sometime can put additional delay in the first case more then the saving it have with lower number of instructions.

PS: I have not tried your code at my end..

Similar Questions
+2 votes
#include <stdio.h>

int main(void)
{
  int a=17;
  scanf("%d",&a);

  int arr[a];

  printf("%lu",sizeof(arr));
}

Memory for array "arr" should be allocated at compile time but in this case it takes the value of "a" from the user(run-time) and allocates the same size for the array.

...