MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

Measure Fast Executing Test Code


Performance tests that execute too quickly for MATLAB to measure accurately are filtered
with an assumption failure. With the matlab.perftest.TestCase.keepMeasuring
method, the testing framework can measure significantly faster code by automatically
determining the number of times to iterate through code and measuring the average
performance.

In your current working folder, create a class-based test, PreallocationTest.m, that
compares different methods of preallocation. Since the test methods include
qualifications, use the startMeasuring and stopMeasuring methods to define
boundaries for the code you want to measure.

classdef PreallocationTest < matlab.perftest.TestCase
methods(Test)
function testOnes(testCase)
testCase.startMeasuring
x = ones(1,1e5);
testCase.stopMeasuring
testCase.verifyEqual(size(x),[1 1e5])
end

function testIndexingWithVariable(testCase)
import matlab.unittest.constraints.IsSameSetAs
testCase.startMeasuring
id = 1:1e5;
x(id) = 1;
testCase.stopMeasuring
testCase.verifyThat(x,IsSameSetAs(1))
end

function testIndexingOnLHS(testCase)
import matlab.unittest.constraints.EveryElementOf
import matlab.unittest.constraints.IsEqualTo
testCase.startMeasuring
x(1:1e5) = 1;
testCase.stopMeasuring
testCase.verifyThat(EveryElementOf(x),IsEqualTo(1))
end

function testForLoop(testCase)
testCase.startMeasuring
for i=1:1e5

33 Unit Testing

Free download pdf