this works ok for me with ldc compiler, gdc does not work on my arch machine so I can not do comparsion to your c++ versin (clang does not work with your c++ code)
import std.stdio : writeln; import std.algorithm.comparison: min; import std.algorithm.iteration: sum; import core.time: MonoTime, Duration; T[] sum_subranges(T)(T[] input, uint range) { import std.array : appender; auto app = appender!(T[])(); if (range == 0) { return app.data; } for (uint i; i < input.length; i=min(i+range, input.length)) { app.put(sum(input[i..min(i+range, input.length)])); } return app.data; } 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) == []); } int main() { import std.range : iota, array; auto v = iota(0,1000000).array; int sum; 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; } On Sun, Aug 13, 2017 at 9:03 AM, Neia Neutuladh via Digitalmars-d-learn < digitalmars-d-learn@puremagic.com> wrote: > On Sunday, 13 August 2017 at 06:09:39 UTC, amfvcg wrote: > >> Hi all, >> I'm solving below task: >> > > Well, for one thing, you are preallocating in C++ code but not in D. > > On my machine, your version of the code completes in 3.175 seconds. > Changing it a little reduces it to 0.420s: > > T[] result = new T[input.length]; > size_t o = 0; > for (uint i; i < input.length; i=min(i+range, input.length)) > { > result[o] = sum(input[i..min(i+range, input.length)]); > o++; > } > return result[0..o]; > > You can also use Appender from std.array. >