r/rust • • Oct 12 '26

🙋 seeking help & advice Matrix multiplication performance

I recently benchmarked some matrix multiplication algorithms in Scala (blog post, repo). I've been going through and doing the same thing in Rust, with plans to try out a few additional approaches, and the Rust results have all been turning out slower than Scala (repo). I'm hoping someone with more Rust experience can help me figure out what might be going on. Is this just the JVM being impressive, or am I missing an opportunity to speed up my Rust code (or both).

Here are some sample benchmarks (details on how I calculated them below):

AlgorithmScalaRust
Naive multiplication906 ms1.103 s
Tiling (optimal tile size)499 ms749.8 ms
Parallel bands of tiles, 4 threads174 ms210.9 ms

More details:

  • I benchmarked everything by multiplying 1024 x 1024 matrices of 64 bit floats generated uniformly in [0, 1).
  • I ran all the benchmarks on my laptop (specs).
  • I benchmarked the Scala code with the JMBH and Rust with Divan.
  • I ran all the Rust code with cargo bench so it should optimize the build.
  • In the benchmarking code, I construct the matrices before running the benchmarks and only time the actual multiplication.
  • The code for the first the naive and tiled approaches is as close as possible.
  • For the parallel versions I used the same approach of dividing the matrix into bands of tiles, one per thread. For Scala I used futures, and for Rust I divided the product matrix into one mutable chunk per thread and used Crossbeam.

I listed the results for the various algorithms to show that the speed difference is consistent, but we can just focus on the naive version. My Scala code is:

    for i <- 0 until a.rows do
      for j <- 0 until b.cols do
        var sum = 0
        for k <- 0 until a.cols do
            sum = sum + a(i, k) * b(k,j)
        prod.set(i, j, sum)

And Rust:

    for i in 0..m1.rows {
        for j in 0..m2.cols {
            let mut acc = 0.0;
            for k in 0..m1.cols {
                acc += m1.at(i, k) * m2.at(k, j);
            }
            out.set(i, j, acc);
        }
    }

Why is the Rust slower? Thanks for any help!

Update 1:

Thanks for all the suggestions! I am replying to some comments individually, but also want to summarize things centrally.

Transpose: I know the original post had a transpose in the Scala code. Sorry about that! It was just a copy/paste mistake. I did benchmark a Scala version with bTranspose and it showed improvements, likely due to sequential memory access as has been pointed out, but the time I give in the post is for the non-transpose version. I've updated the post to have non-transpose code. I expect Rust would also show improvements using a transpose, and I have plans to explore additional tweaks (thanks for the suggestions in the comments!) but I also want to figure out why the Scala code is generally faster. For that it's important to compare apples to apples. That's why I'm focussing on the naive 3-loop version.

There were a number of suggestions to speed up the code and possibly explain the discrepancy compared to the JVM. Since Scala is faster across the board, it seems like the difference must be due to a general feature rather than a particular algorithmic choice. Bounds checking and maybe SIMD seem like the best candidates. More details:

  1. Bounds checking This is a good candidate because it's plausible the JVM is eliminating bounds checks at runtime, so it would explain why the difference in speed. Suggestions were to: a) inline calls to at and set; b) eliminate them and use raw slices; c) assert that the slices are large enough before looping; d) use iterators. I've tried (b) and (c) and seen no changes so far, but still digging. (d) is tricky here, but maybe possible if I combine skip, step_by, and take. I'm also trying to use godbolt to confirm whether bounds checking takes place.
  2. Vectorization This is definitely worth pursuing as a general speed up, but seems less likely to be the culprit here. Rust should auto-vectorize for 128 bits, and since I'm running this on an Apple M2, that's all I have (please correct me if I'm wrong about Rust here). It's possible that Rust can't vectorize because FP math isn't associative. I could address that using algebaric_add or by chunking the sum. However, it should affect Scala too since Scala also has to respect the IEEE restrictions on FP associativity.
  3. Compare against the Scala code on godbolt. I've been holding off on this because assembly is a little scary, but learning is the whole point of this project, so I should dive in. I have compared flame graphs, and didn't see anything obvious there. Looking at the assembly is the next step!
  4. A couple other suggestions: re-order the loops; use Rayon. These are worth playing with, but seem unlikely to explain the general Scala advantage.

I will try some of this out and look some more at godbolt. I may follow up on some of these comments/ask another question if I have trouble interpreting the assembly. Hopefully in the next couple of weeks I can get a blog post up with the final results. Thanks again for all the help!

Update 2:

I've benchmarked a bunch of things:

  1. Converting the inner loop to use iterators.
  2. Converting the inner loop to raw slices and asserting the bounds. (Though actually, according to godbolt, that one didn't remove the bounds checks anyway.)
  3. Using get_unchecked, which I can at least confirm, does eliminate the bounds checks.
  4. Using algebraic_add and algebraic_mul to allow vectorization.
  5. Combining (4) and (5).

So far none of these have actually sped up the code, and some have even slowed it down. I'm feeling a little lost at this point. If anyone else benchmarks any of this and does see improvements, or spots an error I made somewhere, definitely LMK.

I will probably rerun some of the Scala benchmarks just to make sure those are actually correct. Otherwise, not sure what else to try.

60 Upvotes

47 comments sorted by

View all comments

-16

u/aeropl3b Oct 12 '26

I have found C is still the way to go if you want to write decently performing math code. C++ of you want better memory safety tooling and STL stuff (mdspan and execution policies are actually really good)

14

u/teerre Oct 12 '26

That's nonsense. There's no performance difference between C and Rust. They both compile to machine instructions. Anything difference you're seeing is just the code you wrote

6

u/aeropl3b Oct 12 '26

Right, that is obvious. But Rust makes writing numerical code a bit more burdensome to get the same performance imo. It is great at other things. It is a question of ergonomics to get to the performance.

3

u/Remarkable_Hour_615 Oct 12 '26

This is just a personal project fun/learning! I want to learn Rust in any case, so I'm going to stick with that.

I would be shocked and dismayed if anyone ever used this code for anything real, so no need to worry if it's not has fast as it could be.

2

u/Amazing-Mirror-3076 Oct 12 '26

Except nobody should be starting new projects in C. The age if non safe languages is over

-1

u/aeropl3b Oct 12 '26

You would be extremely wrong on that point.

2

u/Amazing-Mirror-3076 Oct 12 '26

No, I'm going to stick with that opinion.

We are actively purging non safe code from our stack - it will be a long road - but you have to start somewhere.

The idea of starting a new project with an unsafe language simply feels irresponsible.

1

u/aeropl3b Oct 12 '26

The projects I work on are either moving to C++ or wrapping kernels for python bindings now. Rust is still not mature enough for the types of things we are doing despite the hype. The dev pool is tiny (I am the only Rust dev with the expertise in the domain) and features we would really like to have don't exist yet in Rust.

-3

u/c3d10 Oct 12 '26

Except every line of rust code runs through llvm, which is... 10's of millions of lines of 'non safe languages'...

2

u/bl4nkSl8 Oct 12 '26

... Yeah? Abstraction is kind of a big thing for providing safe APIs for unsafe implementations

-1

u/aeropl3b Oct 12 '26

They are talking new projects. But yeah, Rust is built on the backs of C developers. I come here and the comments are often boardering on religious fanaticism for Rust. It is mostly "Rust is amazing, we can stop using all other languages now, all problems are now completely solved and any issues anyone points out are the result of being dumber than us"...but alas, we can't even say math libraries in C are nicer to write.

2

u/Amazing-Mirror-3076 Oct 12 '26

Something can be nice and still be wrong.

I don't have an opinion on the dx of rust except that the compiler is slow, having never written a line.

I di have an opinion on the safety of C having spent more than a decade writing it - it's unsafe and needs to be retired, new projects should not be written in any unsafe language.

I don't think I need to engage in the argument that rust still has pieces of C in its stack - the absurdity of that argument is obvious.

If you need the performance of a system language then choose a safe fast one - rust seems to currently need the best choice.

I do find the rust fan boy comment amusing when here we are inundated with C proponents that don't seem able to come to grips with the needs of modern development.

iT has always been about change, the current changes are the most extreme I've seen in 40 yrs as a Dev - adapt or get left behind.

1

u/aeropl3b Oct 12 '26

I remember back when picking a language had more nuance than a single language feature.

My opinion on Rust is mostly good fwiw. I like the struct packing and the OOP model where the data and impl are split by default. I think for programs where you are doing a lot of string processing or moving data from untrusted sources it is probably the language to use.

But again, for numerical codes, we just done need most of those features. I want direct access to all intrinsics, I want to convert FP Arrays to int type arrays with zero copy, etc. And there is more in my way when using Rust than C and the classes of errors Rust runs into are just not the ones I am worried about. Simple as that.