MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

Test Performance Using Classes


This example shows how to create a performance test and regression test for the
fprintf function.

Write Performance Test

Consider the following unit (regression) test. You can run this test as a performance test
using runperf('fprintfTest') instead of runtests('fprintfTest').

classdef fprintfTest < matlab.unittest.TestCase
properties
file
fid
end
methods(TestMethodSetup)
function openFile(testCase)
testCase.file = tempname;
testCase.fid = fopen(testCase.file,'w');
testCase.assertNotEqual(testCase.fid,-1,'IO Problem')

testCase.addTeardown(@delete,testCase.file);
testCase.addTeardown(@fclose,testCase.fid);
end
end

methods(Test)
function testPrintingToFile(testCase)
textToWrite = repmat('abcdef',1,5000000);
fprintf(testCase.fid,'%s',textToWrite);
testCase.verifyEqual(fileread(testCase.file),textToWrite)
end

function testBytesToFile(testCase)
textToWrite = repmat('tests_',1,5000000);
nbytes = fprintf(testCase.fid,'%s',textToWrite);
testCase.verifyEqual(nbytes,length(textToWrite))
end
end
end

The measured time does not include the time to open and close the file or the assertion
because these activities take place inside a TestMethodSetup block, and not inside a

Test Performance Using Classes
Free download pdf