Ich kam zu dem gleichen Problem, damit ich ein paar Tests habe, hier sind einige Ergebnisse 3.4.6 gcc-Version unter Verwendung/CentOS 4
ac und cc Verwendung ifs, aber cc nimmt die Variable von der Kommandozeile so Der Compiler kennt den Wert von "b" zur Kompilierzeit nicht. b.c verwendet
Quellcodes wechseln:
A. C
#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;
}
}
b.c
#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;
}
}
ersten kompilieren wir die Programme ohne Optimierung Fahnen:
Die Ergebnisse sind wie ich dachte, Schalter ist schneller als wenn keine Compiler-Optimierung verwendet wird.
Jetzt erstellen wir -O2 mit:
[email protected] ~ # gcc a.c -o a -O2;gcc b.c -o b -O2;gcc c.c -o c -O2
[email protected] ~ # time ./a
real 0m0.055s
user 0m0.055s
sys 0m0.000s
[email protected] ~ # time ./b
real 0m0.537s
user 0m0.535s
sys 0m0.001s
[email protected] ~ # time ./c 10
real 0m0.056s
user 0m0.055s
sys 0m0.000s
Überraschung Überraschung, beide Programme (A. C und C. C.) mit ifs sind schneller als Schalter (etwa 10 mal!).
Mit 'if's kann der Compiler unter bestimmten Umständen den 'if'-Baum optimieren, um eine Nachschlagetabelle zu verwenden. Dies ist mit aktuellen Compilern viel weniger wahrscheinlich, aber es geht nicht über das hinaus, was der Standard sagt. –