Skip to content

Instantly share code, notes, and snippets.

@ice799
Created October 27, 2009 08: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 ice799/219407 to your computer and use it in GitHub Desktop.
Save ice799/219407 to your computer and use it in GitHub Desktop.
#if 0
In these examples, let's assume that passing more than 2 args to the program is
*not* the case we are optimizing this for.
With that in mind, lets build a sample program with
and without __builtin_expect and compare assembly output.
#endif
/*
no predictor:
sub $0x8,%rsp
cmp $0x3,%edi
jle 0x4004e8 <main+24> ; <===== fail
int3 ; <===== fail
xor %eax,%eax
add $0x8,%rsp
retq
nopl 0x0(%rax)
mov $0x4005ec,%edi
callq 0x4003c0 <puts@plt>
xor %eax,%eax
add $0x8,%rsp
retq
*/
#include <stdio.h>
int main(int argc, char *argv[]) {
if (argc > 3)
asm("int $0x3\n");
else
printf("yo dog\n");
return 0;
}
===
/*
with predictor:
sub $0x8,%rsp
cmp $0x3,%edi
jg 0x4004ea <main+26> ; <==== win
mov $0x4005dc,%edi ; <==== win
callq 0x4003c0 <puts@plt>
xor %eax,%eax
add $0x8,%rsp
retq
int3
jmp 0x4004e3 <main+19>
*/
#include <stdio.h>
#define unlikely(x) __builtin_expect((x),0)
int main(int argc, char *argv[]) {
if (unlikely(argc > 3))
asm("int $0x3\n");
else
printf("yo dog\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment