Quick actions

cmd+k|ctrl+k

Navigation

Languages

Parallel-Matrix-Multiplication

Snippet info

Language

Raku

Visibility

public

Author

221a86612c7785cb6094f25b034cba9994736288

Created

2025-11-26T10:35:24.645362Z

Updated

2025-11-26T15:43:41.89647Z

#!/usr/bin/env raku

#| dot product of two vectors
sub infix:<·>( @a, @b where @a.elems == @b.elems ) {
    [+] @a >>*<< @b
}

#| generic matrix multiplication - cols of @a must equal rows of @b
sub infix:<dot>( @a, @b where @a[0].elems == @b>>.[0].elems) {
    my @b-transposed = [Z] @b;
    
    my UInt $degree = %*ENV<RAKU_PARALLEL_COMPUTATION_DEGREE> // 2;
    my UInt $batch = %*ENV<RAKU_PARALLEL_COMPUTATION_BATCH_SIZE> // 2 ** 15;
    note "Parallel computation using $degree cores and a batch size of $batch elements" if %*ENV<RAKU_PARALLEL_COMPUTATION_DEBUG>;
    
    @a.hyper(:$degree, :$batch).map( -> @r { @b-transposed.map( -> @c { @r · @c } ) })
}

use Test;

plan 1;

my @a =
    [1, 0, 1],
    [2, 1, 1],
    [0, 1, 1],
    [1, 1, 2],
;
my @b = 
    [1, 2, 1],
    [2, 3, 1],
    [4, 2, 2],
;

my @c = 
    [ 5, 4, 3],
    [ 8, 9, 5],
    [ 6, 5, 3],
    [11, 9, 6],
;

#%*ENV<RAKU_PARALLEL_COMPUTATION_DEBUG> = 1;
#%*ENV<RAKU_PARALLEL_COMPUTATION_DEGREE> = 4;
#%*ENV<RAKU_PARALLEL_COMPUTATION_BATCH> = 2 ** 21;

is @a dot @b, @c, "Matrix multiplication example from Wikipedia";

done-testing;
INFO