SHOW:
|
|
- or go back to the newest paste.
| 1 | /** | |
| 2 | * Demo: scalar.d | |
| 3 | * Purpose: Slightly modified source from question on [Stack Overflow](http://stackoverflow.com/questions/5142366/how-fast-is-d-compared-to-c) | |
| 4 | * Original code posted wasn't portable because of dynamic array length type (ulong on Linux, uint on Windows from testing) | |
| 5 | * Replaced platform-dependent types (array.length) with typeof and auto statements. | |
| 6 | * | |
| 7 | * Source was compiled with `rdmd --compiler=ldc2 -O3 -boundscheck=off scalar.d`. | |
| 8 | * Authors: @lars, Erich Gubler (@erichdongubler) | |
| 9 | * Date: 3/30/2015 | |
| 10 | */ | |
| 11 | import std.stdio; | |
| 12 | import std.datetime; | |
| 13 | import std.random; | |
| 14 | ||
| 15 | const long N = 20000; | |
| 16 | const int size = 10; | |
| 17 | ||
| 18 | alias int value_type; | |
| 19 | alias long result_type; | |
| 20 | alias value_type[] vector_t; | |
| 21 | alias typeof(vector_t.init.length) size_type;// Changed this to make portable - Linux is ulong, Win8.1 is uint | |
| 22 | ||
| 23 | value_type scalar_product(const ref vector_t x, const ref vector_t y) {
| |
| 24 | value_type res = 0; | |
| 25 | size_type siz = x.length; | |
| 26 | for (size_type i = 0; i < siz; ++i) | |
| 27 | res += x[i] * y[i]; | |
| 28 | return res; | |
| 29 | } | |
| 30 | ||
| 31 | int main() {
| |
| 32 | auto tm_before = Clock.currTime(); | |
| 33 | ||
| 34 | // 1. allocate and fill randomly many short vectors | |
| 35 | vector_t[] xs; | |
| 36 | xs.length = N; | |
| 37 | for (int i = 0; i < N; ++i) {
| |
| 38 | xs[i].length = size; | |
| 39 | } | |
| 40 | writefln("allocation: %s ", (Clock.currTime() - tm_before));
| |
| 41 | tm_before = Clock.currTime(); | |
| 42 | ||
| 43 | for (int i = 0; i < N; ++i) | |
| 44 | for (int j = 0; j < size; ++j) | |
| 45 | xs[i][j] = uniform(-1000, 1000); | |
| 46 | writefln("random: %s ", (Clock.currTime() - tm_before));
| |
| 47 | tm_before = Clock.currTime(); | |
| 48 | ||
| 49 | // 2. compute all pairwise scalar products: | |
| 50 | result_type avg = cast(result_type) 0; | |
| 51 | for (int i = 0; i < N; ++i) | |
| 52 | for (int j = 0; j < N; ++j) | |
| 53 | avg += scalar_product(xs[i], xs[j]); | |
| 54 | avg = avg / N*N; | |
| 55 | writefln("result: %d", avg);
| |
| 56 | auto time = Clock.currTime() - tm_before; | |
| 57 | writefln("scalar products: %s ", time);
| |
| 58 | ||
| 59 | return 0; | |
| 60 | } |