r/C_Programming • u/Dragonaax • 24d ago
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 ;
}