Fun with matrix multiplication and unsafe code 1


In this post I will compare two methods that perform matrix multiplication. We start by defining the Matrix class:

Next we add the first algorithm to the Matrix class which performs a naive multiplication:

The second method uses unsafe code:

Now it’s time to measure the performance:

In this test we perform 10000 multiplications of two randomly generated matrices with sizes 20×30 and 30×40 using both methods:

Method CPU cycles
unsafe multiplication 4485698
naive multiplication 58762273

The results show that the naive multiplication is slower by a factor of 13 compared to the multiplication using unsafe code and working directly with memory.


Leave a comment

Your email address will not be published. Required fields are marked *

One thought on “Fun with matrix multiplication and unsafe code