How to sum multidimensional arrays?

jmh530 john.michael.hall at gmail.com
Thu Feb 27 16:31:49 UTC 2020


On Thursday, 27 February 2020 at 15:28:01 UTC, p.shkadzko wrote:
> On Thursday, 27 February 2020 at 14:15:26 UTC, p.shkadzko wrote:
>> This works but it does not look very efficient considering we 
>> flatten and then calling array twice. It will get even worse 
>> with 3D arrays.
>
> And yes, benchmarks show that summing 2D arrays like in the 
> example above is significantly slower than in numpy. But that 
> is to be expected... I guess.
>
> D -- sum of two 5000 x 6000 2D arrays: 3.4 sec.
> numpy -- sum of two 5000 x 6000 2D arrays: 0.0367800739913946 
> sec.

What's the performance of mir like?

The code below seems to work without issue.

/+dub.sdl:
dependency "mir-algorithm" version="~>3.7.17"
dependency "mir-random" version="~>2.2.10"
+/
import std.stdio : writeln;
import mir.random : Random, unpredictableSeed;
import mir.random.variable: UniformVariable;
import mir.random.algorithm: randomSlice;

auto rndMatrix(T)(T max, in int rows, in int cols)
{
     auto gen = Random(unpredictableSeed);
     auto rv = UniformVariable!T(0.0, max);
     return randomSlice(gen, rv, rows, cols);
}

void main() {
     auto m1 = rndMatrix(10.0, 2, 3);
     auto m2 = rndMatrix(10.0, 2, 3);
     auto m3 = m1 + m2;

     writeln(m1);
     writeln(m2);
     writeln(m3);
}


More information about the Digitalmars-d-learn mailing list