Guest User

Untitled

a guest
May 28th, 2019
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.77 KB | None | 0 0
  1. double base_c( const double[] values) pure nothrow @nogc @safe
  2. {
  3.     double sum = 0.0;
  4.     for (auto i = 0; i < values.length; ++i)
  5.         sum += values[i] * values[i];
  6.     return sum;
  7. }
  8.  
  9. double base_d(double[] values) pure nothrow @nogc @safe
  10. {
  11.     double sum = 0.0;
  12.     foreach (v; values)
  13.         sum += v * v;
  14.     return sum;
  15. }
  16.  
  17. double d_with_sum(double[] values) @safe pure nothrow
  18. {
  19.     import std.algorithm : sum;
  20.     double[] squares;
  21.     squares[] = values[] * values[];
  22.     return squares.sum;
  23. }
  24.  
  25. double d_with_fold(double[] values) pure @safe
  26. {
  27.     import std.algorithm : fold;
  28.     return values.fold!((r,v) => r + v*v)(0.0);
  29. }
  30.  
  31. void main() @safe
  32. {
  33.     import std.random : uniform, Random, unpredictableSeed;
  34.     import std.stdio : writefln, writeln;
  35.     import std.datetime.stopwatch : StopWatch, Duration;
  36.  
  37.     double[] values;
  38.     auto rnd = Random(unpredictableSeed);
  39.     foreach (i; 0 .. 32_000_000)
  40.         values ~= i; //uniform(0.0f, 10.0, rnd);
  41.  
  42.     Duration t1, t2, t3, t4;
  43.     StopWatch sw;
  44.     enum n = 10;//0_000;
  45.     double r1, r2, r3, r4;
  46.     r1 = r2 = r3 = r4 = 0;
  47.     foreach (_; 0 .. n) {
  48.         sw.reset();
  49.         sw.start();
  50.         r1 += base_c(values);
  51.         sw.stop();
  52.         t1 += sw.peek();
  53.  
  54.         sw.reset();
  55.         sw.start();
  56.         r2 += base_d(values);
  57.         sw.stop();
  58.         t2 += sw.peek();
  59.        
  60.         sw.reset();
  61.         sw.start();
  62.         r3 += d_with_sum(values);
  63.         sw.stop();
  64.         t3 += sw.peek();
  65.        
  66.         sw.reset();
  67.         sw.start();
  68.         r4 += d_with_fold(values);
  69.         sw.stop();
  70.         t4 += sw.peek();
  71.     }
  72.  
  73.     // print res(rX) too for no drop calcs at all
  74.     writefln( "t1=%-30s \tr=%-25.0f", t1/n, r1/n );          
  75.     writefln( "t2=%-30s \tr=%-25.0f", t2/n, r2/n );          
  76.     writefln( "t3=%-30s \tr=%-25.0f", t3/n, r3/n );          
  77.     writefln( "t4=%-30s \tr=%-25.0f", t4/n, r4/n );          
  78. }
Add Comment
Please, Sign In to add comment