1

Suppose I have a function called Test in Matlab as follow: function [f, varargout] = Test(I,varargin)

When I run this function on a specific input, the execution time is 0.019661 Sec.

If I copy the whole body of the function and paste it in a new .m file and name it as Tes1, I would have the same function with a different name like function [f, varargout] = Test1(I,varargin)

Now, when I run function Test1 with same input as Test, the execution time is 0.055111 Sec.

The question is: what is the reason for that? Your answer is appreciated.

3
  • 6
    First of all, I'd suggest to run these functions in the loop like 1000 times to see if there is significant difference between execution times. Single comparison can not be measured as solid proof. Also, there is a difference between data storage schemes - this page Commented Mar 18, 2015 at 16:28
  • Thanks very much Pavel, your comment worked completely. So: Elapsed time for Test: 0.013483 Sec. Elapsed time for Test1: 0.013518 Sec Commented Mar 18, 2015 at 16:52
  • 2
    @aryodgh That initial jump in computation time is probably from Matlab compiling the new m-file (since it took twice a long, I don't think it was a system thing). But yeah, as a rule of thumb, a dozen (for intensive function) to a few thousand (for less-taxing functions) iterations is a better measure of performance. Commented Mar 18, 2015 at 16:59

1 Answer 1

2

This is likely due to various caching effects. First of all, your operating might cache the file, so the second time you read it it will be faster. Second, also Matlab itself might do tricks, like running the Just-in-Time compiler the first time you call a function, and caching the results for the next time you call it.

Better than writing some for-loop by hand to time a function would be to use the timeit function. This always runs the function several times to 'warm up the cache', and then calls it a certain number of times in a loop, depending on how much time it takes (i.e. a handful of times for a slow function, or 100000 times for a really fast one). It is included in recent versions of Matlab, for older versions it is available on the file-exchange.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.