D outperformed by C++, what am I doing wrong?

ikod via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 13 01:27:14 PDT 2017


On Sunday, 13 August 2017 at 08:13:56 UTC, amfvcg wrote:
> On Sunday, 13 August 2017 at 08:00:53 UTC, Daniel Kozak wrote:
>> my second version on ldc takes 380ms and c++ version on same 
>> compiler (clang), takes 350ms, so it seems to be almost same
>>
>
> Ok, on ideone (ldc 1.1.0) it timeouts, on dpaste (ldc 0.12.0) 
> it gets killed.
> What version are you using?
>
> Either way, if that'd be the case - that's slick. (and ldc 
> would be the compiler of choice for real use cases).

import std.stdio : writeln;
import std.algorithm.comparison: min;
import std.algorithm.iteration: sum;
import core.time: MonoTime, Duration;
import std.range;
import std.algorithm;

auto s1(T)(T input, uint r) {
     return input.chunks(r).map!sum;
}

T[] sum_subranges(T)(T[] input, uint range)
{
     T[] result;
     if (range == 0)
     {
         return result;
     }
     for (uint i; i < input.length; i=min(i+range, input.length))
     {
         result ~= sum(input[i..min(i+range, input.length)]);
     }
     return result;
}

unittest
{
     assert(sum_subranges([1,1,1], 2) == [2, 1]);
     assert(sum_subranges([1,1,1,2,3,3], 2) == [2, 3, 6]);
     assert(sum_subranges([], 2) == []);
     assert(sum_subranges([1], 2) == [1]);
     assert(sum_subranges([1], 0) == []);
     assert(s1([1,1,1], 2).array == [2, 1]);
     assert(s1([1,1,1,2,3,3], 2).array == [2, 3, 6]);
}
int main()
{
     int sum;
     MonoTime beg0 = MonoTime.currTime;
     for (int i=0; i < 100; i++)
         sum += s1(iota(1000000),2).length;
     MonoTime end0 = MonoTime.currTime;
     writeln(end0-beg0);
     writeln(sum);

     sum = 0;
     int[1000000] v;
     for (int i=0; i < 1000000; ++i)
         v[i] = i;
     MonoTime beg = MonoTime.currTime;
     for (int i=0; i < 100; i++)
         sum += cast(int)sum_subranges(v,2).length;
     MonoTime end = MonoTime.currTime;
     writeln(end-beg);
     writeln(sum);
     return sum;
}

Gives me

5 μs and 2 hnsecs
50000000
3 secs, 228 ms, 837 μs, and 4 hnsecs
50000000



More information about the Digitalmars-d-learn mailing list