Skip to content

Instantly share code, notes, and snippets.

@kripken
Created June 30, 2025 20:39
Show Gist options
  • Save kripken/09ad895764cd6cd3b7a8a6c13c643c93 to your computer and use it in GitHub Desktop.
Save kripken/09ad895764cd6cd3b7a8a6c13c643c93 to your computer and use it in GitHub Desktop.
//
// Branch hints benchmark: 30% faster with the right hint (LIKELY=0),
// 20% slower with the wrong one (LIKELY=1), compared to no hint.
//
#include <iostream>
#include <vector>
#ifdef LIKELY
#define hint(x) __builtin_expect((x), LIKELY)
#else
#define hint(x) (x)
#endif
int main() {
// Fill a large vector with almost all zeroes.
const int N = 1024 * 1024;
std::vector<int> vec(N);
vec[42] = 1;
// Do some silly computation on this vector.
int a = 0;
int b = 0;
for (int i = 0; i < 1000; i++) {
for (int j = 1; j < N; j++) {
if (hint(vec[j])) {
// This vector entry is non-zero, which almost never happens.
a += vec[j]; // Use the value to prevent optimizations.
vec[j] = i; // Add a write to prevent optimizations.
} else {
b++;
}
}
}
std::cout << "a: " << a << '\n';
std::cout << "b: " << b << '\n';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment