A little benchmark in D and C

bearophile via digitalmars-d-ldc digitalmars-d-ldc at puremagic.com
Fri Jul 4 08:40:25 PDT 2014


Through Reddit I've found a little benchmark. Here there is a D 
version, followed by a C99 version.

I compile with:
ldmd2 -O -release -inline -noboundscheck test1.d
gcc -O3 -std=c99 test2.c -o test2

I use gcc 4.8.0.

On an old PC the run-time of C version is about 5.2 seconds, 
while the D version compiled with the latest ldc2 runs in about 
26 seconds (almost 5 times slower).

Bye,
bearophile

---------------------------------

// D version.
import core.stdc.stdio;

enum int t = 20;

bool isEvenlyDivisible(in int i, in int a, in int b)
pure nothrow @safe {
     if (i > b)
         return true;
     else
         return (a % i == 0) && isEvenlyDivisible(i + 1, a, b);
}

void run() nothrow {
     int i = 10;
     while (!isEvenlyDivisible(2, i, t))
         i += 2;
     printf("%d\n", i);
}

void main() {
     for (int i = 0; i < 5; i++)
       run;
}

---------------------------------

// C version.
#include <stdio.h>
#include <stdbool.h>

const int t = 20;

bool isEvenlyDivisible(const int i, const int a, const int b) {
     if (i > b)
         return true;
     else
         return (a % i == 0) && isEvenlyDivisible(i + 1, a, b);
}

void run() {
     int i = 10;
     while (!isEvenlyDivisible(2, i, t))
         i += 2;
     printf("%d\n", i);
}

int main() {
     for (int i = 0; i < 5; i++)
       run();
     return 0;
}

---------------------------------


More information about the digitalmars-d-ldc mailing list