Skip to content

Instantly share code, notes, and snippets.

@AlexisTM
Last active June 11, 2021 06:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlexisTM/2754f6b373bf40b544408a631abeb5ba to your computer and use it in GitHub Desktop.
Save AlexisTM/2754f6b373bf40b544408a631abeb5ba to your computer and use it in GitHub Desktop.
C/C++ performance magic functions (prevent optimization)
/**
* Those functions are related to: https://www.youtube.com/watch?v=nXaxk27zwlk&t=2446s
*
* They are used to allow to benchmark functions with -O3 that would otherwise be removed because it is unused.
*
* escape(&object) prevents object to be optimized out
* "This ASM code has some unknowable side effects and possibly stored the pointer globally"
* clobber() tells the compiler some asm might be reading the whole memory
* "This ASM code could probably read/write to all memory" => observe all memory
*/
void escape(void* p) {
asm volatile("" : : "g"(p) : "memory");
}
void clobber() {
asm volatile("" : : : "memory");
}
@AlexisTM
Copy link
Author

Example:

void benchmark() {
    std::vector<int> v;
    v.reserve(1);
    escape(&v.data());
    v.push_back(42);
    clobber();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment