Skip to content

Instantly share code, notes, and snippets.

@denwarenjii
Created September 3, 2025 20:48
Show Gist options
  • Select an option

  • Save denwarenjii/6e94d1006abc9acd505d3885035609f7 to your computer and use it in GitHub Desktop.

Select an option

Save denwarenjii/6e94d1006abc9acd505d3885035609f7 to your computer and use it in GitHub Desktop.
unpredictable
/* https://stackoverflow.com/questions/28961405/
is-there-a-code-that-results-in-50-branch-prediction-miss */
/* gcc -Wall -Wextra -Wpedantic -g3 unpredictable.c -o undpredictable */
/* perf stat -e cycles,instructions,branches,branch-misses,cache-references,\
* cache-misses,L1-dcache-loads,L1-dcache-load-misses,dTLB-load-misses,\
* iTLB-load-misses ./unpredictable */
#include <stdio.h>
#include <time.h>
#define RDRAND
#define LCG_A 1103515245
#define LCG_C 22345
#define LCG_M 2147483648
#define ULL64 unsigned long long
ULL64 generated;
ULL64 rand_lcg(ULL64 seed)
{
#ifdef RDRAND
ULL64 result = 0;
asm volatile ("rdrand %0;" : "=r" (result));
return result;
#else
return (LCG_A * seed + LCG_C) % LCG_M;
#endif
}
ULL64 rand_rec1()
{
generated = rand_lcg(generated) % 1024;
if (generated < 512)
return generated;
else return rand_rec1();
}
ULL64 rand_rec2()
{
generated = rand_lcg(generated) % 1024;
if (!(generated >= 512))
return generated;
else return rand_rec2();
}
#define BROP(num, sum) \
num = rand_lcg(generated); \
asm volatile("": : :"memory"); \
if (num % 2) \
sum += rand_rec1(); \
else \
sum -= rand_rec2();
#define BROP5(num, sum) BROP(num, sum) BROP(num, sum) BROP(num, sum) BROP(num, sum) BROP(num, sum)
#define BROP25(num, sum) BROP5(num, sum) BROP5(num, sum) BROP5(num, sum) BROP5(num, sum) BROP5(num, sum)
#define BROP100(num, sum) BROP25(num, sum) BROP25(num, sum) BROP25(num, sum) BROP25(num, sum)
int main()
{
int i = 0;
int iterations = 500000;
ULL64 num = 0;
ULL64 sum = 0;
generated = rand_lcg(0) % 54321;
for (i = 0; i < iterations; i++)
{
BROP100(num, sum);
// ... repeat the line above 10 times
}
printf("Sum = %llu\n", sum);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment