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

4 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2023-2-15
"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 2023-2-15
编辑:Kutsop 2023-2-15
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.

请先登录,再进行评论。

采纳的回答

Rik
Rik 2023-2-15
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 个评论
Kutsop
Kutsop 2023-2-15
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

标签

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by