Why do some commands run faster or slower in the command line than an M.file?
이전 댓글 표시
Why do some commands run faster and some slower in the command line than in an M.file?
I'm trying to speed up the time it takes my code to run. I looked at the online tutorial and generated a test script using the pre-allocating arrays example from:
If I run the loops with the index of a million (as in the example) it takes to long to run over 30 min; therefore, my test.m file loops are reduced to 100000.
When I run my code I get:
Elapsed time is 29.813208 seconds.
Elapsed time is 0.005239 seconds.
When I execute the same commands from the "command line" I get:
>> clear
>> tic;x = 0;for k = 2:100000;x(k) = x(k-1) + 5;end;toc
Elapsed time is 29.517578 seconds.
>> clear
>> tic;x = zeros(1, 100000);x = 0;for k = 2:100000;x(k) = x(k-1) + 5;end;toc
Elapsed time is 29.077256 seconds.
>>
Notice there is very little difference between in time between the first loop (not pre-allocated) and second loop (pre-allocated). Also it appears that the first loop was a little faster from the command line than from the M file.
M-file code is as follows:{
% Test.m file for checking cpu compute time W/ & w/o preallocating arrays
clear; % clear variables (for testing purposes)
clc; % clears "output" screen
tic %start stopwatch timer
x = 0;
for k = 2:100000
x(k) = x(k-1) + 5;
end;
toc %end stopwatch timer
clear; % clear variables (for testing)
tic %start stopwatch timer
x = zeros(1, 100000); % pre-allocate x
for k = 2:100000
x(k) = x(k-1) + 5;
end
toc %end stopwatch timer
}
System info: Matlab 7.5.0 (R2007b) XP Home (32 bit) on Mac Book Pro (MBP) Intel Core 2 Duo P8600 @ 2.4Ghz 2GB of ram
채택된 답변
추가 답변 (1개)
Shashank Prasanna
2013년 2월 27일
1 개 추천
In general in a MATLAB file the JIT has the opportunity to preallocate memory and perform other run time optimization. You will most likely see better performance running the code in a MATLAB file, you may also see better performance on repeated execution in a MATLAB file.
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!