erichdongubler

scalar3.d

Mar 30th, 2015
1,649
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.87 KB | None | 0 0
  1. /**
  2.  * Demo: scalar3.d
  3.  * Purpose: Compare with scalar2.d - replaces most for loops with foreach
  4.  *    The author noticed that there was a speedup between DMD 2.066.1 and 2.067.0,
  5.  *    there was a harsher penalty for using foreach here.
  6.  * Authors: Erich Gubler, erichdongubler@gmail.com
  7.  * Date: 3/30/2015
  8.  */
  9. import std.stdio : writeln;
  10. import std.datetime : Clock, Duration;
  11. import std.array : uninitializedArray;
  12. import std.random : uniform;
  13.  
  14. alias result_type = long;
  15. alias value_type = int;
  16. alias vector_t = value_type[];
  17. alias index_type = typeof(vector_t.init.length);// Make index integrals portable - Linux is ulong, Win8.1 is uint
  18.  
  19. immutable long N = 20000;
  20. immutable int size = 10;
  21.  
  22. // Replaced for loops with appropriate foreach versions
  23. value_type scalar_product(in ref vector_t x, in ref vector_t y) { // "in" is the same as "const" here
  24.   value_type res = 0;
  25.   for(index_type i = 0; i < size; ++i)
  26.     res += x[i] * y[i];
  27.   return res;
  28. }
  29.  
  30. int main() {
  31.   auto tm_before = Clock.currTime;
  32.   auto countElapsed(in string taskName) { // Factor out printing code
  33.     writeln(taskName, ": ", Clock.currTime - tm_before);
  34.     tm_before = Clock.currTime;
  35.   }
  36.  
  37.   // 1. allocate and fill randomly many short vectors
  38.   vector_t[] xs = uninitializedArray!(vector_t[])(N);// Avoid default inits of inner arrays
  39.   foreach(ref x; xs)
  40.     x = uninitializedArray!(vector_t)(size);// Avoid more default inits of values
  41.   countElapsed("allocation");
  42.  
  43.   foreach(ref x; xs)
  44.     foreach(ref val; x)
  45.       val = uniform(-1000, 1000);
  46.   countElapsed("random");
  47.  
  48.   // 2. compute all pairwise scalar products:
  49.   result_type avg = 0;
  50.   foreach(const ref x; xs)
  51.     foreach(const ref y; xs)
  52.       avg += scalar_product(x, y);
  53.   avg /= N ^^ 2;// Replace manual multiplication with pow operator
  54.   writeln("result: ", avg);
  55.   countElapsed("scalar products");
  56.  
  57.   return 0;
  58. }
Add Comment
Please, Sign In to add comment