Is there some advantage to knowing at compile time how many iterations should be done of a for loop?
For example, in some situations, can the compiler produce an executable that will run faster given this:
#define ITERATIONS 10
int foo()
{
for (int i=0; i < ITERATIONS; i++){
do_something();
}
}
than given this:
int foo(int iterations)
{
for (int i=0; i < iterations; i++){
do_something();
}
}
If this is not universally the case, what are those situations?
My concern is in the specific case of OpenCL, so I’m also interested to know if this is different to C.
I tested in a fairly realistic situation using GCC. When the number of loops is known at compile time, I get this:
When it’s not, I get this:
So it was able to optimize the fixed number of iterations slightly better by changing to a count down to zero loop rather than a count up loop. If nothing else, this uses a bit less code cache.
With higher optimizations levels, it fully unrolls a loop that invokes an external function ten times. Presumably, it wouldn’t do that unless it thought it was better. And it surely can’t do that if the number of iterations is unknown.
Short answer: Fixed numbers of iterations give compilers more options. That should result in very slightly better code at least some of the time.