Dawn
Dawn

Reputation: 3628

Matlab time limit for function execution

I'm looking to limit the execution of function in Matlab, so if it won't return answer in X seconds the call will be aborted.
I know it's possible with the 2011 Matlab version using timeout, but I've got the 2010 version of Matlab. Is it still possible to limit the execution time of the function?

Upvotes: 3

Views: 5645

Answers (1)

jcollomosse
jcollomosse

Reputation: 672

As others have pointed out you can't do this natively in Matlab. However on Unix systems e.g. Linux or Solaris I have previously used a bit of a dirty hack to achieve the desired effect.

Rather than calling your .m file as a function with parameters, save all the parameter data into a .mat file and write a shell command to invoke Matlab and run your .m file e.g. myfunc.m as a standalone routine e.g.

!bash -c "ulimit -t 3;matlab -nodisplay < myfunc.m"

This would limit myfunc.m to a CPU execution time of 3 second. Note that is CPU not including any disk access etc. There are other flags you can pass to ulimit if you need some other behaviour.

Inside myfunc.m you'd have to save the data myfunc.m wants to return into a .mat file and load it up again in your calling program. Bit of a nasty hack but I have tested it and it works. Note the use of the bash shell for the internal ulimit command.

Upvotes: 3

Related Questions