Skip to content

Instantly share code, notes, and snippets.

@kaja47
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaja47/b4c5c8bfa5f5898bc252 to your computer and use it in GitHub Desktop.
Save kaja47/b4c5c8bfa5f5898bc252 to your computer and use it in GitHub Desktop.
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