MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1
Script-Based Performance Test Function-Based Performance Test
vectorSize = 1e7;

%% Ones Function
x = ones(1,vectorSize);

%% Indexing With Variable
id = 1:vectorSize;
x(id) = 1;

%% Indexing On LHS
x(1:vectorSize) = 1;

%% For Loop
for i=1:vectorSize
x(i) = 1;
end

function tests = preallocationTest
tests = functiontests(localfunctions);
end

function testOnes(testCase)
vectorSize = getSize();
x = ones(1,vectorSize());
end

function testIndexingWithVariable(testCase)
vectorSize = getSize();
id = 1:vectorSize;
x(id) = 1;
end

function testIndexingOnLHS(testCase)
vectorSize = getSize();
x(1:vectorSize) = 1;
end

function testForLoop(testCase)
vectorSize = getSize();
for i=1:vectorSize
x(i) = 1;
end
end

function vectorSize = getSize()
vectorSize = 1e7;
end

Run Performance Test

Run the performance test using runperf.

results = runperf('preallocationTest.m')

Running preallocationTest
.......... .......... .......... ..
Done preallocationTest
__________

results =

33 Unit Testing

Free download pdf