Speed comparison of two functions using tic/toc

8 visualizzazioni (ultimi 30 giorni)
Hi, I am supposed to write a function and then to compare my code with built-in MATLAB-function (A\b), how can I do it? I know I can use tic toc function like this:
function [ z ] = My_Function(A,b)
tic
my code
toc
%Comparison with built-in
tic
MATLABfunction(A,b)
toc
end
But is there any function i could use to do deeper comparison and print the results? I would like the output of my function to look like this:
My_Function(A,b)
ans =
...
Time elapsed using your function is: XY seconds, time elapsed using built-in MATLAB function is YX seconds.
Thank you very much in advance

Risposta accettata

John D'Errico
John D'Errico il 23 Apr 2017
Modificato: John D'Errico il 23 Apr 2017
What "deeper" comparison do you think is possible? You already know about the existence of tic and toc, although in many cases, timeit will be a better choice. But if you have some custom block of code, then timeit will not work, unless you encapsulate the entire block of code in its own function.
My point is, if you want some deeper analysis, then you need to explain what "deeper" means to you.
Regardless, it appears that all you need to learn how to do is save the results of the call to toc as a variable, and then display a line of text, converting the number of seconds used into a character string.
So read the help for toc, disp, and num2str.
help toc
help disp
help num2str
If tmycode is the time required for your own code, and tbuiltin is the time for the built-in code to run, then just use disp. Something vaguely like this:
disp(['Time elapsed using your function is:', ...
num2str(tmycode),' seconds',...
'time elapsed using built-in MATLAB function is ',...
num2str(tbuiltin),' seconds.'])

Più risposte (0)

Categorie

Scopri di più su Resizing and Reshaping Matrices in Help Center e File Exchange

Tag

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by