mardi 4 avril 2017

How to do index rotation

Which would be the preferred way of accessing a fixed size array as a circular list?

void foo()
{
  volatile int data[10];
  for(unsigned i = 0; i < 999; ++i)
  {
    data[ i % 10 ] = i;
  }
}


void bar()
{
  volatile int data[10];
  unsigned j = 0;
  for(unsigned i = 0; i < 999; ++i)
  {
    data[ j ] = i;
    j = j > 8 ? 0 : j + 1;
  }
}

I have always been under the impression, that the first form is far, as branching is avoided. However, with gcc 6.2 targeted for x86_64 with -O1, foo() seems to invoke a costly mul instruction and the jump count is the same. Which approach should be the default?

The question is valid for both tagged languages.

Aucun commentaire:

Enregistrer un commentaire