Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
branch prediction test
#include <stdio.h>
#include <stdlib.h>
#include <immintrin.h>
// gcc -std=c99 -D IS_RAND=0 branch-test.c ; for i in -1 -2 1 3 2 4 8 16; do echo '### ' $i; perf stat -r5 -o _stats_pred_base --append ./a.out $i; echo; done
// gcc -O3 -std=c99 -D IS_RAND=0 branch-test.c ; for i in -1 -2 1 3 2 4 8 16; do echo '### ' $i; perf stat -r5 -o _stats_pred_o3 --append ./a.out $i; echo; done
// gcc -std=c99 -D IS_RAND=1 branch-test.c ; for i in 8 16 32 64 128 256; do echo '### ' $i; perf stat -r5 -o _stats_rand_base --append ./a.out $i; echo; done
// gcc -O3 -std=c99 -D IS_RAND=1 branch-test.c ; for i in 8 16 32 64 128 256; do echo '### ' $i; perf stat -r5 -o _stats_rand_o3 --append ./a.out $i; echo; done
unsigned long x = 47;
unsigned long xorShiftRandom() {
x ^= (x << 21);
x ^= (x >> 35);
x ^= (x << 4);
return x;
}
int main (int argc, char *argv[]) {
int param = atol(argv[1]);
if (param == -1) param = 0x80000000;
if (param == -2) param = 0xffffffff;
if (param == 0)
return 1;
#if IS_RAND == 0
// predictable pattern
int sum = 0;
for (int i = 0; i < 100000000; i++) {
if ((i & param) == 0) sum += 1;
}
printf("condition (i & %d) == 0\n", param);
#else
// random pattern
unsigned long *vals = malloc(sizeof(unsigned long) * param);
for (int i = 0; i < param; i++) {
vals[i] = xorShiftRandom();
}
int sum = 0;
for (int i = 0; i < 100000000; i++) {
unsigned long r = vals[i & (param - 1)];
if ((r & 1) == 0) sum++;
}
printf("random pattern length %d\n", param);
#endif
printf("sum = %d\n", sum);
}
gcc -std=c99 -D IS_RAND=0 branch-test.c ; for i in -1 -2 1 3 2 4 8 16; do echo '### ' $i; perf stat -r5 -o _stats_pred_base --append ./a.out $i; echo; done
gcc -O3 -std=c99 -D IS_RAND=0 branch-test.c ; for i in -1 -2 1 3 2 4 8 16; do echo '### ' $i; perf stat -r5 -o _stats_pred_o3 --append ./a.out $i; echo; done
gcc -std=c99 -D IS_RAND=1 branch-test.c ; for i in 8 16 32 64 128 256; do echo '### ' $i; perf stat -r5 -o _stats_rand_base --append ./a.out $i; echo; done
gcc -O3 -std=c99 -D IS_RAND=1 branch-test.c ; for i in 8 16 32 64 128 256; do echo '### ' $i; perf stat -r5 -o _stats_rand_o3 --append ./a.out $i; echo; done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment