tyler569 icon

C vs D

tyler569 | PRO | 04/22/17 11:02:56 PM UTC | 0 ⭐ | 1108 👁️ | Never ⏰ | []
text |

2.61 KB

|

None

|

0 👍

/

0 👎

tyler@mac ~/Documents> gcc -O3 test.c -octest ; ./ctest
C fast : 3010us
C slow : 22876us
tyler@mac ~/Documents> clang -O3 test.c -octest ; ./ctest
C fast : 3297us
C slow : 26991us
tyler@mac ~/Documents> dmd -L-w -w -O -run test.d
D together : 485us
D idiomatic: 1267us
D fast     : 5071us
D slow     : 23423us
tyler@mac ~/Documents> ldc2 -L-w -w -O -run test.d
D together : 606us
D idiomatic: 646us
D fast     : 692us
D slow     : 29892us
  ##########################################################################
# test.c
 #include <stdio.h>
#include <time.h>
 #define SIZE 1024
 int arr[SIZE][SIZE];
 void add_1_fast() {
    for (int i=0; i<SIZE; i++) {
        for (int j=0; j<SIZE; j++) {
            arr[i][j] += 1;
        }
    }
}
 void add_1_slow() {
    for (int i=0; i<SIZE; i++) {
        for (int j=0; j<SIZE; j++) {
            arr[j][i] += 1;
        }
    }
}
 int main() {
    clock_t x, y;
     x = clock();
    add_1_fast();
    y = clock();
     if (CLOCKS_PER_SEC == 1000000) {
        printf("C fast : %lius\n", y - x);
    } else {
        printf("C fast : %fus\n", (double)(y - x) / CLOCKS_PER_SEC * 1000000);
    }
     x = clock();
    add_1_slow();
    y = clock();
     if (CLOCKS_PER_SEC == 1000000) {
        printf("C slow : %lius\n", y - x);
    } else {
        printf("C slow : %fus\n", (double)(y - x) / CLOCKS_PER_SEC * 1000000);
    }
}
 ###################################################################################
# test.d
 import std.stdio;
import std.datetime;
 enum size = 1024;
 int[size][size] arr;
 auto add_1_together() {
    foreach (ref x; arr) {
        x[] += 1;
    }
}
 auto add_1_idiomatic() {
    foreach (ref x; arr) {
        foreach (ref y; x) {
            y += 1;
        }
    }
}
 auto add_1_fast() {
    for (int i=0; i<size; i++) {
        for (int j=0; j<size; j++) {
            arr[i][j] += 1;
        }
    }
}
 auto add_1_slow() {
    for (int i=0; i<size; i++) {
        for (int j=0; j<size; j++) {
            arr[j][i] += 1;
        }
    }
}
 void main() {
     StopWatch sw1, sw2, sw3, sw4;
     sw1.start();
    add_1_together();
    writeln("D together : ", sw1.peek().usecs, "us");
    sw1.stop();
     sw2.start();
    add_1_idiomatic();
    writeln("D idiomatic: ", sw2.peek().usecs, "us");
    sw2.stop();
     sw3.start();
    add_1_fast();
    writeln("D fast     : ", sw3.peek().usecs, "us");
    sw3.stop();
     sw4.start();
    add_1_slow();
    writeln("D slow     : ", sw4.peek().usecs, "us");
    sw4.stop();
     writeln(arr[45][199]);
 }

Comments