Advertisement
Guest User

scalar.d

a guest
Mar 30th, 2015
338
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.80 KB | None | 0 0
  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.  *
  6.  *     Source was compiled with `rdmd --compiler=ldc2 -O3 -boundscheck=off  scalar.d`.
  7.  * Authors: @lars, Erich Gubler (@erichdongubler)
  8.  * Date: 3/30/2015
  9.  */
  10. import std.stdio;
  11. import std.datetime;
  12. import std.random;
  13.  
  14. const long N = 20000;
  15. const int size = 10;
  16.  
  17. alias int value_type;
  18. alias long result_type;
  19. alias value_type[] vector_t;
  20. alias typeof(vector_t.init.length) size_type;// Changed this to make portable - Linux is ulong, Win8.1 is uint
  21.  
  22. value_type scalar_product(const ref vector_t x, const ref vector_t y) {
  23.   value_type res = 0;
  24.   size_type siz = x.length;
  25.   for (size_type i = 0; i < siz; ++i)
  26.     res += x[i] * y[i];
  27.   return res;
  28. }
  29.  
  30. int main() {  
  31.   auto tm_before = Clock.currTime();
  32.  
  33.   // 1. allocate and fill randomly many short vectors
  34.   vector_t[] xs;
  35.   xs.length = N;
  36.   for (int i = 0; i < N; ++i) {
  37.     xs[i].length = size;
  38.   }
  39.   writefln("allocation: %s ", (Clock.currTime() - tm_before));
  40.   tm_before = Clock.currTime();
  41.  
  42.   for (int i = 0; i < N; ++i)
  43.     for (int j = 0; j < size; ++j)
  44.       xs[i][j] = uniform(-1000, 1000);
  45.   writefln("random: %s ", (Clock.currTime() - tm_before));
  46.   tm_before = Clock.currTime();
  47.  
  48.   // 2. compute all pairwise scalar products:
  49.   result_type avg = cast(result_type) 0;
  50.   for (int i = 0; i < N; ++i)
  51.     for (int j = 0; j < N; ++j)
  52.       avg += scalar_product(xs[i], xs[j]);
  53.   avg = avg / N*N;
  54.   writefln("result: %d", avg);
  55.   auto time = Clock.currTime() - tm_before;
  56.   writefln("scalar products: %s ", time);
  57.  
  58.   return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement