Hello,
I am trying to play around with a simple program and its performance and would like to unroll a for loop a certain number of times. Is this possible?
The reason for why I want to do it is that my friend did it in C and their program instantly became significantly faster.
Edit:
I did try the manual unrolling via inline for (but without early breaks) and am once again faster hehe
Edit2:
Nevermind, I added the early returns to genuinely make the code equivalent and it’s now marginally slower than before. I am kinda out of obvious ideas. I could try to do some simd things but not today.
Yes, if you can do it in C, you can probably do it in Zig.
Without knowing your code, I can try to explain the theory behind loop unrolling. You would have to apply it to your specific loop.
Say you have an array of 1000 items and you wanted to unroll it 4 times.
A normal zig loop would be:
for (some_items) |item| {
// do something on that item
const x = doSomething(item);
result += x;
}
To unroll that loop, you would have to “batch” up the operations instead of one at a time.
for (0..@divExact(some_items.len, 4)) |offset| {
const a = doSomething(some_items[offset]);
const b = doSomething(some_items[offset + 1]);
const c = doSomething(some_items[offset + 2]);
const d = doSomething(some_items[offset + 3]);
result += a + b + c + d;
}
That’s the theory anyway. As you can see, you can unroll it any number of times, but you will have to benchmark to see how much it helps in a given situation.
Hm okay I had the same Idea, just thought I would nest loops and make the inner one an inline for, the reason why I stopped is because this forces me to include a bunch of early returns and the function itself is very cheap so I didn’t trust myself sufficiently to keep the calculating of indices at a minimum. I guess I’ll just try it out anyways.
This was kind of the reason I posted this, I thought “I wonder if there is an easier way that does this for me and may even leverage llvm”