Created
June 4, 2016 18:47
-
-
Save vtjnash/1460ba303c2cd4df0dd7ff13f50b4d15 to your computer and use it in GitHub Desktop.
branch prediction confusion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdint.h> | |
#include <stdio.h> | |
#include <inttypes.h> | |
#include <string.h> | |
__attribute__((noinline)) int footest0(); | |
__attribute__((noinline)) int footest1(); | |
int (*ppfootest[1])() = {&footest0}; | |
int foo; | |
__attribute__((noinline)) | |
int footest0() | |
{ | |
ppfootest[0] = footest1; | |
return foo++; | |
} | |
__attribute__((noinline)) | |
int footest1() | |
{ | |
ppfootest[0] = footest0; | |
return foo--; | |
} | |
int main(int argc, char** argv) | |
{ | |
(void)argc; | |
int sum = 0; | |
switch (argv[1][0]) | |
{ | |
case '1': { | |
for (int i = 0; i < 100000000; i++) { | |
sum += (i & 1) == 0 ? footest0() : footest1(); | |
} | |
break; | |
} | |
case '2': { | |
for (int i = 0; i < 100000000; i++) { | |
sum += ppfootest[0](); | |
} | |
break; | |
} | |
case '3': { | |
for (int i = 0; i < 100000000; i++) { | |
int (*pfootest)() = (i & 1) == 1 ? &footest0 : &footest1; | |
sum += pfootest(); | |
} | |
break; | |
} | |
case '8': { // WARNING: don't use a lower number :P | |
for (int i = 0; i < 100000000; i++) { | |
sum += footest0(); | |
} | |
break; | |
} | |
default: | |
printf("bad input\n"); | |
} | |
return sum; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment