Effacer les filtres
Effacer les filtres

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

4 vues (au cours des 30 derniers jours)
Kutsop
Kutsop le 15 Fév 2023
Commenté : Kutsop le 15 Fév 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 commentaires
Stephen23
Stephen23 le 15 Fév 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 le 15 Fév 2023
Modifié(e) : Kutsop le 15 Fév 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.

Connectez-vous pour commenter.

Réponse acceptée

Rik
Rik le 15 Fév 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 commentaire
Kutsop
Kutsop le 15 Fév 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

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Startup and Shutdown dans Help Center et File Exchange

Tags

Produits


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by