Woeful performance of D compared to C++
Sean Kelly
sean at f4.ca
Thu Jan 18 13:54:38 PST 2007
I tried running these under Tango with DMD on Win32 (as it's the setup I
currently have). Here are my slightly altered programs to make the two
a bit more comparable. First, the D code:
import tango.stdc.stdlib;
import tango.stdc.stdio;
void main() {
const uint n = 10_000_000;
ubyte doors;
uint wins, wins_switching;
for (uint i; i < n; ++i) {
doors |= cast(ubyte)(1 << rand() % 3);
if (doors & 1) {
++wins;
} else {
++wins_switching;
}
doors = 0;
}
printf("Wins switching: %d [%f%%]\n", wins_switching,
(wins_switching / cast(double) n) * 100);
printf("Wins without switching: %d [%f%%]\n", wins,
(wins / cast(double) n) * 100);
}
And now the C++ code:
#include <cstdlib>
#include <cstdio>
int main() {
unsigned char doors = 0;
const unsigned int n = 10000000;
unsigned int wins = 0, wins_switching = 0;
for (unsigned int i = 0; i < n; ++i) {
unsigned char r = 1 << (rand() % 3);
doors |= r; // place the car behind a random door
if (doors & 1) { // choose zero'th door, same as random choice
++wins;
} else {
++wins_switching;
}
doors ^= r; // zero the door with car
}
const double d = n / 100;
printf("Wins switching: %d [%f%%]\n", wins_switching,
(wins_switching / (double) n) * 100);
printf("Wins without switching: %d [%f%%]\n", wins,
(wins / (double) n) * 100);
}
C:> dmd -O -inline -release dtest
C:> dmc -o ctest.cpp
Here are the results for three runs of the D app:
Execution time: 1.323 s
Execution time: 1.005 s
Execution time: 1.125 s
And three runs of the C++ app:
Execution time: 1.149 s
Execution time: 1.202 s
Execution time: 1.304 s
The numbers above aren't quite as accurate as those using "time" on
Unix, but they're sufficient for a rough comparison. That said, DMD and
DMC perform pretty much the same once the variable of IOStreams vs.
writefln is removed.
Sean
More information about the Digitalmars-d
mailing list