필터 지우기
필터 지우기

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

조회 수: 4 (최근 30일)
Kutsop
Kutsop 2023년 2월 15일
댓글: Kutsop 2023년 2월 15일
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