How to sum multidimensional arrays?

9il ilyayaroshenko at gmail.com
Thu Feb 27 16:39:15 UTC 2020


On Thursday, 27 February 2020 at 16:31:49 UTC, jmh530 wrote:
> 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);
> }

The same as numpy for large matrixes because the cost is memory 
access. Mir+LDC will be faster for small matrixes because it will 
flatten the inner loop and use SIMD instructions.

Few performances nitpick for your example to be fair with 
benchmarking againt the test:
1. Random (default) is slower then Xorfish.
2. double is twice larger then int and requires twice more 
memory, so it would be twice slower then int for large matrixes.

Check the prev. post, we have posted almost in the same time ;)
https://forum.dlang.org/post/izoflhyerkiladngyrov@forum.dlang.org


More information about the Digitalmars-d-learn mailing list