Functional vs simple code
Timon Gehr
timon.gehr at gmx.ch
Tue Oct 2 15:11:31 PDT 2012
On 10/02/2012 10:48 PM, ixid wrote:
> Without optimization the range and algorithm method takes about 10 times
> as long as the simple code below it, with no array bounds checking and
> optimization it takes six times as long. Why is the difference so huge?
> I'd expect a moderate overhead but that's a big difference.
>
> module main;
> import std.stdio, std.algorithm, std.range, std.datetime;
>
> enum MAX = 10_000_000UL;
>
> void main() {
> StopWatch sw;
> sw.start;
>
> auto sum1 = MAX.iota.map!(x => x * x).reduce!"a + b";
>
> sw.peek.msecs.writeln("msecs");
> sum1.writeln;
> sw.start;
>
> ulong sum2 = 0;
> foreach(i;0..MAX)
> sum2 += i * i;
>
> sw.peek.msecs.writeln("msecs");
>
> sum2.writeln;
> }
$ cat ixidbench.d
module main;
import std.stdio, std.algorithm, std.range, std.datetime;
enum MAX = 10_000_000_000UL;
void main() {
StopWatch sw;
sw.start;
auto sum1 = MAX.iota.map!(x => x * x).reduce!"a + b";
sw.stop;
sw.peek.msecs.writeln("msecs");
sum1.writeln;
sw.reset;
sw.start;
ulong sum2 = 0;
foreach(i;0..MAX)
sum2 += i * i;
sw.stop;
sw.peek.msecs.writeln("msecs");
sum2.writeln;
}
$ ldmd2 -O -release -inline ixidbench.d -ofixidbench
$ ./ixidbench
6528msecs
7032546979563742720
7518msecs
7032546979563742720
More information about the Digitalmars-d-learn
mailing list