Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Demo: scalar3.d
- * Purpose: Compare with scalar2.d - replaces most for loops with foreach
- * The author noticed that there was a speedup between DMD 2.066.1 and 2.067.0,
- * there was a harsher penalty for using foreach here.
- * Authors: Erich Gubler, erichdongubler@gmail.com
- * Date: 3/30/2015
- */
- import std.stdio : writeln;
- import std.datetime : Clock, Duration;
- import std.array : uninitializedArray;
- import std.random : uniform;
- alias result_type = long;
- alias value_type = int;
- alias vector_t = value_type[];
- alias index_type = typeof(vector_t.init.length);// Make index integrals portable - Linux is ulong, Win8.1 is uint
- immutable long N = 20000;
- immutable int size = 10;
- // Replaced for loops with appropriate foreach versions
- value_type scalar_product(in ref vector_t x, in ref vector_t y) { // "in" is the same as "const" here
- value_type res = 0;
- for(index_type i = 0; i < size; ++i)
- res += x[i] * y[i];
- return res;
- }
- int main() {
- auto tm_before = Clock.currTime;
- auto countElapsed(in string taskName) { // Factor out printing code
- writeln(taskName, ": ", Clock.currTime - tm_before);
- tm_before = Clock.currTime;
- }
- // 1. allocate and fill randomly many short vectors
- vector_t[] xs = uninitializedArray!(vector_t[])(N);// Avoid default inits of inner arrays
- foreach(ref x; xs)
- x = uninitializedArray!(vector_t)(size);// Avoid more default inits of values
- countElapsed("allocation");
- foreach(ref x; xs)
- foreach(ref val; x)
- val = uniform(-1000, 1000);
- countElapsed("random");
- // 2. compute all pairwise scalar products:
- result_type avg = 0;
- foreach(const ref x; xs)
- foreach(const ref y; xs)
- avg += scalar_product(x, y);
- avg /= N ^^ 2;// Replace manual multiplication with pow operator
- writeln("result: ", avg);
- countElapsed("scalar products");
- return 0;
- }
Add Comment
Please, Sign In to add comment