Range of random numbers

Christophe Travert travert at phare.normalesup.org
Wed Apr 25 09:02:13 PDT 2012


"bearophile" , dans le message (digitalmars.D.learn:35148), a écrit :
> Why don't you write a little benchmark to compare the performance 
> of the two versions?

Because I'm interested in the code's meaning for the human reader, not 
the performance.

I actually think : "map!(_=> uniform(a, b))(repeat(0))" is better, 
because it puts the call to uniform first, and the _ indicates that the 
rest is unimportant.


For you curiosity, this is the benchmark using:
gdc (GCC) 4.7.0 20120322 (gdc 0.31 - r805:0414cec152c7, using dmd 2.057)
and
gdc -O3 testRNG.d && ./a.out


import std.array, std.range, std.algorithm, std.random, std.stdio, 
std.datetime;

auto uniformRange1(T1, T2, T3)(T1 a, T2 b, T3 gen)
{
  return map!((x) {return x();} ) (repeat((){return uniform(a, b, gen);}));
}

auto uniformRange2(T1, T2, T3)(T1 a, T2 b, T3 gen)
{
  return map!((x) { return uniform(a, b, gen); })(repeat(0));
}

auto uniformRange3(T1, T2, T3)(T1 a, T2 b, T3 gen)
{
  return map!((x) { return uniform(a, b, gen); })(cycle([0]));
}

void f1() { auto ur = array(take(uniformRange1(0, 10, Xorshift(1)), 
1000)); }
void f2() { auto ur = array(take(uniformRange2(0, 10, Xorshift(1)), 
1000)); }
void f3() { auto ur = array(take(uniformRange3(0, 10, Xorshift(1)), 
1000)); }

void main() {
  auto b=benchmark!(f1, f2, f3)(1000);
  writeln(b[0].to!("seconds",double),"s,  ", b[1].to!("seconds",double),
            "s, ", b[2].to!("seconds",double),"s." );
  // outputs :
  // 0.040437s,  0.0393537s, 0.0486439s
}


f2 performs 23% better than f3, and 3% better than f1.

-- 
Christophe


More information about the Digitalmars-d-learn mailing list