double base_c( const double[] values) pure nothrow @nogc @safe { double sum = 0.0; for (auto i = 0; i < values.length; ++i) sum += values[i] * values[i]; return sum; } double base_d(double[] values) pure nothrow @nogc @safe { double sum = 0.0; foreach (v; values) sum += v * v; return sum; } double d_with_sum(double[] values) @safe pure nothrow { import std.algorithm : sum; double[] squares; squares[] = values[] * values[]; return squares.sum; } double d_with_fold(double[] values) pure @safe { import std.algorithm : fold; return values.fold!((r,v) => r + v*v)(0.0); } void main() @safe { import std.random : uniform, Random, unpredictableSeed; import std.stdio : writefln, writeln; import std.datetime.stopwatch : StopWatch, Duration; double[] values; auto rnd = Random(unpredictableSeed); foreach (i; 0 .. 32_000_000) values ~= i; //uniform(0.0f, 10.0, rnd); Duration t1, t2, t3, t4; StopWatch sw; enum n = 10;//0_000; double r1, r2, r3, r4; r1 = r2 = r3 = r4 = 0; foreach (_; 0 .. n) { sw.reset(); sw.start(); r1 += base_c(values); sw.stop(); t1 += sw.peek(); sw.reset(); sw.start(); r2 += base_d(values); sw.stop(); t2 += sw.peek(); sw.reset(); sw.start(); r3 += d_with_sum(values); sw.stop(); t3 += sw.peek(); sw.reset(); sw.start(); r4 += d_with_fold(values); sw.stop(); t4 += sw.peek(); } // print res(rX) too for no drop calcs at all writefln( "t1=%-30s \tr=%-25.0f", t1/n, r1/n ); writefln( "t2=%-30s \tr=%-25.0f", t2/n, r2/n ); writefln( "t3=%-30s \tr=%-25.0f", t3/n, r3/n ); writefln( "t4=%-30s \tr=%-25.0f", t4/n, r4/n ); }