Why is sum(f,1) slower than sum(g,2) for g=f'?

4 visualizzazioni (ultimi 30 giorni)
Kutsop
Kutsop il 15 Feb 2023
Commentato: Kutsop il 15 Feb 2023
So I'm trying to optimize my code and I came across something that doesn't immediately make sense to me but I think is INCREDIBLY important for me to understand.
In the sample code below I found that summing the transpose of my matrix along the second dimmension is 3 times faster than summing the original matrix. Why is this?
f = rand(3,10000);
g = f';
tic
for k = 1:1000000
sum(f,1);
end
toc
%Elapsed time is 28.528823 seconds.
tic
for k = 1:1000000
sum(g,2);
end
toc
%Elapsed time is 9.325141 seconds.
  2 Commenti
Stephen23
Stephen23 il 15 Feb 2023
"Why is sum(f,1) slower than sum(f',2)?"
But that is not what you tested: your code excludes the transpose operation. For a fairer comparison include the transpose:
n = 1e5;
f = rand(3,10000);
tic
for k = 1:n
A = sum(f,1);
end
toc
Elapsed time is 1.522836 seconds.
%Elapsed time is 28.528823 seconds.
tic
for k = 1:n
B = sum(f.',2);
end
toc
Elapsed time is 1.805595 seconds.
Kutsop
Kutsop il 15 Feb 2023
Modificato: Kutsop il 15 Feb 2023
I disagree, I only need to tranpose the matrix once. If you're referring to the title of the post, yes it was misleading, but I was trying to keep things simple. The code accuretly describes the things I'm curios about which is, why is the sum the tranpose of a matrix along 1 dimmension, faster than summing the original matrix along the other dimmension. I updated the title.

Accedi per commentare.

Risposta accettata

Rik
Rik il 15 Feb 2023
I expect this has to do with how a matrix is stored in memory. If I recall correctly, this is column major, so summing along row requires jumping around in the list, while summing along the columns is just following the raw data.
If you had put the conjugate in the test, I expect the result to flip.
  1 Commento
Kutsop
Kutsop il 15 Feb 2023
Thank you! I think you are corrrect! I had never heard "column-major" before so i did some more searching and found supporting evidence on StackOverflow which I've included below for any future folks interested in this topic:
https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Startup and Shutdown in Help Center e File Exchange

Tag

Prodotti


Release

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by