On 2/16/13 12:21 PM, Gopan wrote:
For iterating through a ranges of indices in a circular way, I have seen
people coding like

int i=0;
while(true)
{
...
i = (i+1)%10;
}

People argue i = (i+1)%10 is less costly to the combination below.
++i;
if(i==10)
i = 0;

If the comparison instruction takes only one cycle, how is this argument
correct? Please let me know if that argument is incorrect.

Thanks,
Gopan.

The general argument is that code with branches may be slower than straight-line code on superscalar architectures. In this particular case the test-based code is likely to be cheaper, which can be easily shown by profiling. For details paste this:

uint fun1(uint x) {
  return (x + 1) % 10;
}

uint fun2(uint x) {
  return x == 10 ? 0 : x + 1;
}

into http://d.godbolt.org and take a look at the generated code. It contains no jumps.


Andrei

Reply via email to