choxsword
choxsword

Reputation: 3369

why dose the first loop always runs faster than the second one?

especially,the larger the number of cycles is,the more obvious the difference becomes.

test in g++ without optimization

int main()
{
  int a[]={0,0};
  int b[]={0,0};
  //first loop
  for(unsigned int i=0;i<0x00FFFFFF;i++)
  {
     a[0]++;a[1]++; 
  }

  //second loop
  for(unsigned int i=0;i<0x00FFFFFF;i++)
  {
     b[0]++;b[0]++; //yes it's b[0] not b[1]
  }

  return 0;
}

Somebody may not believe me,me either.But in this code the first loop is at least two times faster than the second one.

Upvotes: 1

Views: 131

Answers (1)

Barmar
Barmar

Reputation: 782295

I suspect it's a pipelining issue. In the first loop you're writing to two different memory locations, so the second addition doesn't need to wait for the first one to finish, and the CPU can do both at once.

In the second loop, you're incrementing the same variable both times, so the second one has to wait for the first one to finish. This slows down the pipeline.

Upvotes: 2

Related Questions