Woeful performance of D compared to C++

rael at seesig.com rael at seesig.com
Thu Jan 18 12:17:11 PST 2007


In other benchmarks I've seen, D seems quite competitive with C/C++.

I seem to have written a very simple program that shows D in a very
poor light compared to C++.  I wonder if it is my inexperience.

I am using dmd 1.0, and g++ 4.1.1 under Linux Fedora Core 6, running
on a 3.0 GHz Pentium 4 with 1 gig of RAM.

The program is a simulation of the Monty Hall problem (see Wikipedia).

Here is the D program:

import std.random;
import std.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;
    }

    writefln("Wins switching: %d [%f%%]", wins_switching,
             (wins_switching / cast(double) n) * 100);
    writefln("Wins without switching: %d [%f%%]", wins,
             (wins / cast(double) n) * 100);
}

Compiled with:

% dmd -I/opt/dmd/src/phobos -O -inline monty.d -ofmonty_d
gcc monty.o -o monty_d -m32 -lphobos -lpthread -lm 

and here is the C++:

#include <iostream>
#include <cstdlib>

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;
    std::cout << "Win % switching: " << (wins_switching / d)
              << "\nWin % no switching: " << (wins / d) << '\n';
}

Compiled with:

% g++ -O3 -o monty_cc

Execution times (best of 5):

% time monty_d
Wins switching: 6665726 [66.657260%]
Wins without switching: 3334274 [33.342740%]

real    0m2.444s
user    0m2.442s
sys     0m0.002s

% time monty_cc
Win % switching: 66.6766
Win % no switching: 33.3234

real    0m0.433s
user    0m0.432s
sys     0m0.001s


Any help would be appreciated.

Thanks.


Bill
--
Bill Lear
r * e * @ * o * y * a * c * m
* a * l * z * p * r * . * o *




More information about the Digitalmars-d mailing list