Random Numbers Generation - For Loop VS 3D Matrix
이전 댓글 표시
Hello, I have a question regarding MATLAB's performance while generating random numbers. This is a pretty straightforward situation, I have two versions of the same code, one generates random number vectors in a for loop and saves them in a 3D matrix, and the other version generates the random numbers all at once in a 3D Matrix using simply rand() function. It just so happens that the "for loop" version is faster than the "no for loop" version after a certain size of the random 3D matrix. I have discussed this with my peers and no one seems to understand why this is. Does anyone know why this happens? Thanks!
PS: This code was tried on different machines running Windows and macOS, enough RAM was avaliable and capable processors were used.
Code:
clear all
m = 10^4;
N = 10^3;
tic
r = zeros(N,3,m);
for n = 1:m
r(:,1:2,n) = rand([N,2]) - 1/2;
r(:,3,n) = rand([N,1]) - 1;
end
toc
clear r
tic
r = rand(N,3,m) - 1;
r(:,1:2,:) = r(:,1:2,:) + 1/2;
toc
채택된 답변
추가 답변 (1개)
Ameer Hamza
2020년 5월 6일
편집: Ameer Hamza
2020년 5월 9일
2 개 추천
It not unheard of and definitely not surprising. Thanks to JIT, for loops are not as slow as one might thinks they are. I guess that rand() might be creating some temporary arrays, since memory operations are expensive, which might explain the extra time. Or it might have some extra logic to maintain the uniformity of random numbers. However, the exact reason is difficult to pinpoint since the source code for rand() is not available. Read here for examples
Read about JIT here
댓글 수: 2
Rodrigo Gonçalves
2020년 5월 9일
John D'Errico
2020년 5월 9일
편집: John D'Errico
2020년 5월 9일
+1. I've added an answer of my own only because the use of the profiler is an important piece of information, and to explain the use of timeit, and finally, to show that there is a third way to write this, that does in fact improve the time required below that of the loops.
Since my answer explains that really, the problem is not in the one large call to rand, but in the fact that there were multiple additions done when only one addition needed to be done for each array element. The looped version did only one add per element, but then so does my test3 code, and it was the most efficient version of all.
카테고리
도움말 센터 및 File Exchange에서 Performance and Memory에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!