How to measure time of matrix multiplication in matab?

조회 수: 3 (최근 30일)
Azmar Ismael
Azmar Ismael 2024년 7월 9일
댓글: Stephen23 2024년 7월 10일
I am using R2023b in case that is important.
For the sake of a project, I am trying to measure the average time of matlab when it multiplies a 96 x 192 matrix with a 192 x 1 matrix.
I have used the following code:
repeats = 100;
tTot = 0;
m = 96;
n = 192;
for j = 0:repeats
A = rand([m,n]);
A(:,1) = 1;
b = rand([n,1]);
tic
c = A * b;
tTot = tTot + toc;
end
tAvg = tTot/repeats
I have run this script a few times on my computer with different values for "repeats":
  • If I set repeats to 1, I get the time it takes to complete a matrix multiplication is ~1.25e-04
  • If I set repeats to 10, I get the time it takes to complete a matrix multiplication is ~8.75e-05
  • If I set repeats to 100, I get the time it takes to complete a matrix multiplication is ~5e-06
It seems quite strange to me that the average changed so much if I increase the value for repeats, so my questions are: Am I doing something wrong when I am measuring the average time? If yes, what am I doing wrong?
  댓글 수: 2
Aquatris
Aquatris 2024년 7월 10일
편집: Aquatris 2024년 7월 10일
Adding to the @Steven Lord answer, keep in mind execution time of the exact same thing can be different depending on the available resources of your PC at the time you run the code
Stephen23
Stephen23 2024년 7월 10일
"It seems quite strange to me that the average changed so much if I increase the value for repeats"
The MATLAB JIT engine would be perfectly capable of deciding to apply different code optimisations depending on the number of iterations that are performed:
Whether it does is another question.

댓글을 달려면 로그인하십시오.

답변 (1개)

Steven Lord
Steven Lord 2024년 7월 9일
As stated on this documentation page, "Sometimes programs run too fast for tic and toc to provide useful data. If your code is faster than 1/10 second, consider measuring it running in a loop, and then average to find the time for a single run."
Generate the matrices once then wrap the for loop in a tic and toc pair. Inside the loop all you'd do is perform the matrix multiplication.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by