0

I am new to the preprocessor, I rarely use it, so this question might seem silly. In my C program I discovered that a for loop which had a fixed start and end known at compile time was causing some performance issues. I temporarily solved this by manually rolling it out, however that seems to be a bit dirty. Is there a way to tell the preprocessor to turn this:

for(int i = 0; i < 8; i++)
{
    doSomeThingWithI(i, [...]);
    doSomeMoreStuffWithIt(i, [...]);
    foo();
    [...]
}

into this:

doSomeThingWithI(0, [...]);
doSomeMoreStuffWithIt(0, [...]);
foo();
[...]

doSomeThingWithI(1, [...]);
doSomeMoreStuffWithIt(1, [...]);
foo();
[...]

[...]

The important thing is that I have to use "i" inside the loop.

11
  • 2
    Possible duplicate of Writing a while loop in the C preprocessor Commented Feb 18, 2017 at 16:56
  • 3
    I doubt the loop is your problem... Commented Feb 18, 2017 at 16:56
  • 1
    I expected this comment. The loop only contains few instructions, is however executed per pixel in a raycaster. The difference between the non-rolled-out and the rolled-out for loop in terms of performance measured in fps is about 10.8% Commented Feb 18, 2017 at 17:02
  • 1
    I don't think there is a portable/standard compliant way to instruct the compiler to unroll a loop. Loop unrolling is usually part of the optimization phase, so you can try (if you didn't already) to play around with the compiler optimization settings (check the manual of your compiler for options). Otherwise I'd just use the manually unrolled loop. Commented Feb 18, 2017 at 17:08
  • 3
    I am a preprocessor noob, I rarely use it, Please try to keep it that way, You end up with more readable and debuggable code Commented Feb 18, 2017 at 17:08

1 Answer 1

2

You could always hard-code it like this (replace printf with your functions):

#include <stdio.h>

#define LOOP_8(X) X X X X X X X X

int main() {
   int i = 0;
   LOOP_8(printf("Loop number %d\n", i++);)
}

But that's probably way too ugly to use in real code.

Sign up to request clarification or add additional context in comments.

3 Comments

I like the nerdiness of it.
thought about that, but I still have to declare i and add one per cycle.
@Addi Assuming you're compiling with gcc, have you tried using -funroll-loops?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.