Switch implementation
bearophile
bearophileHUGS at lycos.com
Tue Sep 28 17:23:13 PDT 2010
Iain Buclaw:
> Oh, it was my *original* intention to test runtime speed. However, the time to
> compile just stood out little more like a sore thumb than what I anticipated.
If your purpose is to test runtime speed, use a more natural number of cases like 10 or 20 or even 50 :-)
So I have done a better test, see below for the code.
Timings, NLOOPS = 100_000, best of 6, seconds:
DMD: 7.70
GCC: 2.42
gcc 4.5.1, -Wall -O3 -s
dmd 2.049, -O -release -inline
--------------------------------
// D code
import std.c.stdio: printf;
enum int NLOOPS = 100000;
int c1, c2, c3;
void f1() { c1++; }
void f2() { c2++; }
void f3() { c3++; }
int main() {
int i, j;
for (i = 0; i < NLOOPS; i++) {
for (j = 0; j < 5000; j++) {
switch (j) {
case 140: f1(); break;
case 300: f1(); break;
case 1280: f1(); break;
case 1540: f1(); break;
case 1660: f1(); break;
case 1770: f2(); break;
case 2150: f2(); break;
case 2190: f1(); break;
case 2530: f2(); break;
case 2560: f2(); break;
case 2590: f1(); break;
case 2660: f1(); break;
case 2720: f2(); break;
case 3010: f1(); break;
case 3100: f1(); break;
case 3390: f2(); break;
case 3760: f1(); break;
case 3970: f2(); break;
case 4050: f1(); break;
case 4140: f1(); break;
case 4360: f2(); break;
case 4540: f1(); break;
case 4600: f2(); break;
case 4720: f2(); break;
case 4730: f2(); break;
case 4740: f2(); break;
case 4880: f2(); break;
case 4950: f1(); break;
default: f3();
}
}
}
printf("%d %d %d\n", c1, c2, c3);
return 0;
}
--------------------------------
// C code
#include "stdio.h"
#define NLOOPS 100000
int c1, c2, c3;
void f1() { c1++; }
void f2() { c2++; }
void f3() { c3++; }
int main() {
int i, j;
for (i = 0; i < NLOOPS; i++) {
for (j = 0; j < 5000; j++) {
switch (j) {
case 140: f1(); break;
case 300: f1(); break;
case 1280: f1(); break;
case 1540: f1(); break;
case 1660: f1(); break;
case 1770: f2(); break;
case 2150: f2(); break;
case 2190: f1(); break;
case 2530: f2(); break;
case 2560: f2(); break;
case 2590: f1(); break;
case 2660: f1(); break;
case 2720: f2(); break;
case 3010: f1(); break;
case 3100: f1(); break;
case 3390: f2(); break;
case 3760: f1(); break;
case 3970: f2(); break;
case 4050: f1(); break;
case 4140: f1(); break;
case 4360: f2(); break;
case 4540: f1(); break;
case 4600: f2(); break;
case 4720: f2(); break;
case 4730: f2(); break;
case 4740: f2(); break;
case 4880: f2(); break;
case 4950: f1(); break;
default: f3();
}
}
}
printf("%d %d %d\n", c1, c2, c3);
return 0;
}
Bye,
bearophile
More information about the Digitalmars-d
mailing list