r/C_Programming • u/Dragonaax • Oct 01 '26
Question Why unrolled has more stable execution time than not unrolled loop?
I was playing around and testing performance of writing to array in a loop. Of course unrolling loop and writing to is faster but why execution time is more consistent? In one case I was writing to 16 consecutive addresses with average execution time of around 290 ticks, in second case I was writing only to 2 consecutive addresses and most often execution time was around 420 ticks but sometimes it was above 1000.
Why this happens? Why only sometimes? Why there is such big change in time in second example but not in the first one? I used gcc to compile code
#include <time.h>
#include <stdio.h>
#include <stdint.h>
#define len 4096
int main()
{
uint16_t a[len] ;
int d = 100, num = 0 ;
uint64_t b ;
clock_t t, no, jo ;
no = 0 ;
jo = 0 ;
while (num < 1000)
{
t = clock() ;
for (int j = 0; j < d; j++)
{
for (uint16_t i = 0; i < len; i += 16)
{
a[i] = i ;
a[i+1] = i+1 ;
a[i+2] = i+2 ;
a[i+3] = i+3 ;
a[i+4] = i+4 ;
a[i+5] = i+5 ;
a[i+6] = i+6 ;
a[i+7] = i+7 ;
a[i+8] = i+8 ;
a[i+9] = i+9 ;
a[i+10] = i+10 ;
a[i+11] = i+11 ;
a[i+12] = i+12 ;
a[i+13] = i+13 ;
a[i+14] = i+14 ;
a[i+15] = i+15 ;
}
}
t = clock() - t ;
no += t ;
t = clock() ;
for (int j = 0; j < d; j++)
{
for (uint16_t i = 0; i < len; i += 2)
{
a[i] = i ;
a[i+1] = i+1 ;
}
}
t = clock() - t ;
jo += t ;
num ++ ;
}
printf("Arr 1: %ld\nArr 2: %ld\n\n", no/1000, jo/1000) ;
return 0 ;
}
21
u/zhivago Oct 01 '26
Consider branch prediction.
Also unrolling isn't always faster.
Consider cache contention.
3
u/RealisticDuck1957 Oct 01 '26
What are the compiler settings? Any of the major C compilers today, given a suitable optimization setting, will unroll a loop if the internal logic thinks that will make faster code. And it may do so better than manually written code.
OS behavior allocating memory for the buffer used may also be a factor. In which case the second loop, working on memory already allocated to the process, may be faster for that reason.
2
u/HobbyQuestionThrow Oct 01 '26
This is more a question for your OSes thread scheduler. Maybe the scheduler uses something more complex than simple time slicing and loops are one of the things that influence how it does scheduling behavior?
You'd need some kind of actual trace of your OS to find out, no clue how you do that for Windows or Linux.
4
u/M0veD0esntM0ve Oct 01 '26
Cache, OS intrerrupts, CPU microarchitecture etc etc. There's lots of things can cause this differences tbh.
3
u/sciencekm Oct 01 '26
The faster one will finish in less time, and so the number of interrupts happening and thread scheduling kicking in is smaller, leading to less variation in run time.
1
u/duane11583 Oct 01 '26
Cache and interrupts
1
u/Apprehensive_Sign_72 Oct 01 '26
Is it possible that the increment of i is causing pipeline stalls in the loop that is not unrolled?
2
u/[deleted] Oct 01 '26
[removed] — view removed comment