I came to the same problem, so I did some tests, here are some results obtained with gcc version 3.4.6 / centos 4
ac and cc use ifs, but cc takes a variable from the command line, so the compiler does not know the value of "b" at compile time. bc uses a switch
source codes:
ac
#include <stdint.h> int main(){ uint32_t i,b=10,c; for(i=0;i<1000000000;i++){ if(b==1) c=1; if(b==2) c=1; if(b==3) c=1; if(b==4) c=1; if(b==5) c=1; if(b==6) c=1; if(b==7) c=1; } }
bc
#include <stdint.h> int main(){ uint32_t i,b=10,c; for(i=0;i<1000000000;i++){ switch(b){ case 1: c=1; break; case 2: c=1; break; case 3: c=1; break; case 4: c=1; break; case 5: c=1; break; case 6: c=1; break; case 7: c=1; break; } } }
c.c
#include <stdint.h> int main(int argc, char **argv){ uint32_t i,b=10,c; b=atoi(argv[1]); for(i=0;i<1000000000;i++){ if(b==1) c=1; if(b==2) c=1; if(b==3) c=1; if(b==4) c=1; if(b==5) c=1; if(b==6) c=1; if(b==7) c=1; } }
first we compile programs without optimization flags:
root@dev2 ~
The results, as I thought, switch faster than if compiler optimization is not used.
Now we compile using -O2:
root@dev2 ~
An amazing surprise: both programs (ac and cc), using ifs, are faster (about 10 times!) Than the switch.
Cosmin
source share