Filter löschen
Filter löschen

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

4 Ansichten (letzte 30 Tage)
Kutsop
Kutsop am 15 Feb. 2023
Kommentiert: Kutsop am 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 Kommentare
Stephen23
Stephen23 am 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 am 15 Feb. 2023
Bearbeitet: Kutsop am 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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Rik
Rik am 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 Kommentar
Kutsop
Kutsop am 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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Startup and Shutdown finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by