Is it worth recoding simpler versions of built-in MATLAB functions to speed up performance?

조회 수: 4(최근 30일)
Using ADiGator, a package for the automatic differentiation of MATLAB functions, I stumbled across the issue that the package does not accept any files involving functions that take "varargin" inputs - i.e. I am having to copy and paste the code from a lot the built in MATLAB functions that take varargin, alter them and save them as local functions in my own directory. The resulting functions are significantly simpler but of course come with a smaller range of functionality.
This got me thinking - is there any point in doing this for most built-in functions? i.e. let's say I know that in a particular script/function that is being looped thousands of times, I will only need to use ode45 in a particular format (i.e. a certain number/type of inputs) - is there anything wrong with making a simpler version of the ode45 code that would, presumably work faster (although, of course, only being able to take that specific format of input arguments), to be used specifically for that purpose? I.e. is this a bad programming practice (in the same way as e.g. using global variables is advised against)?

채택된 답변

Bruno Luong
Bruno Luong 2022년 11월 26일
편집: Bruno Luong 2022년 11월 26일
You are free to strip down anything you want, just don't use the same name as the stock function.
As soon as you change the specification, functionality you ought to change the name of the function.
Though your example of ode45 is not well chosen to illustrate the point. ode45 is basically designed to be accurate but slow. It would not accelerate if you call it with certian type of input. If you want to accelerate, write your own ode solver and trade off the accuracy.
  댓글 수: 5
Walter Roberson
Walter Roberson 2022년 11월 27일
There are times when it can make a real difference.
Suppose for example that you have code that loops doing lots and lots of ismember against a constant array. Every call it has to validate the parameter types and sizes. Then ismember checks to see if the second parameter is already sorted and if not runs a sort operation. Then it calls a binary search internal function.
You can reduce the overhead by batching more values in the first parameter. And sometimes that can work quite well. But sometimes you still end up with lots and lots of calls to ismember.
In the case of an already sorted second parameter, it turns out that you can reduce the overhead noticeably by not calling ismember and instead directly calling the internal binary search routine. The name of that routine has changed at least once so you need a unit test to be sure any given function name will work in a new release.

댓글을 달려면 로그인하십시오.

추가 답변(0개)

범주

Find more on Testing Frameworks in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by