erichdongubler

scalar2.d

Mar 30th, 2015
746
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Demo: scalar2.d
  3.  * Purpose: Compare with scalar.d and scalar.cpp
  4.  *     Used uninitializedArray to avoid default inits for scalars in xs
  5.  *
  6.  *   Changes with little or no performance effect:
  7.  *     Factored out printing code and replaced writefln with writeln
  8.  *     Replaced platform-dependent types (array.length) with typeof and auto statements.
  9.  *     Changed imports to be selective
  10.  *     Used pow operator (^^) instead of manual multiplication for final step of calculating average
  11.  *     Removed the size_type and replaced appropriately with the index_type alias
  12.  *
  13.  *     Source was compiled with `rdmd --compiler=ldc2 -O3 -boundscheck=off scalar2.d`.
  14.  * Authors: Erich Gubler (@erichdongubler)
  15.  * Date: 3/30/2015
  16.  */
  17. import std.stdio : writeln;
  18. import std.datetime : Clock, Duration;
  19. import std.array : uninitializedArray;
  20. import std.random : uniform;
  21.  
  22. alias result_type = long;
  23. alias value_type = int;
  24. alias vector_t = value_type[];
  25. alias index_type = typeof(vector_t.init.length);// Make index integrals portable - Linux is ulong, Win8.1 is uint
  26.  
  27. immutable long N = 20000;
  28. immutable int size = 10;
  29.  
  30. // Replaced for loops with appropriate foreach versions
  31. value_type scalar_product(in ref vector_t x, in ref vector_t y) { // "in" is the same as "const" here
  32.   value_type res = 0;
  33.   for(index_type i = 0; i < size; ++i)
  34.     res += x[i] * y[i];
  35.   return res;
  36. }
  37.  
  38. int main() {
  39.   auto tm_before = Clock.currTime;
  40.   auto countElapsed(in string taskName) { // Factor out printing code
  41.     writeln(taskName, ": ", Clock.currTime - tm_before);
  42.     tm_before = Clock.currTime;
  43.   }
  44.  
  45.   // 1. allocate and fill randomly many short vectors
  46.   vector_t[] xs = uninitializedArray!(vector_t[])(N);// Avoid default inits of inner arrays
  47.   for(index_type i = 0; i < N; ++i)
  48.     xs[i] = uninitializedArray!(vector_t)(size);// Avoid more default inits of values
  49.   countElapsed("allocation");
  50.  
  51.   for(index_type i = 0; i < N; ++i)
  52.     for(index_type j = 0; j < size; ++j)
  53.       xs[i][j] = uniform(-1000, 1000);
  54.   countElapsed("random");
  55.  
  56.   // 2. compute all pairwise scalar products:
  57.   result_type avg = 0;
  58.   for(index_type i = 0; i < N; ++i)
  59.     for(index_type j = 0; j < N; ++j)
  60.       avg += scalar_product(xs[i], xs[j]);
  61.   avg /= N ^^ 2;// Replace manual multiplication with pow operator
  62.   writeln("result: ", avg);
  63.   countElapsed("scalar products");
  64.  
  65.   return 0;
  66. }
RAW Paste Data Copied