问题描述
我希望限制Matlab中函数的执行,因此,如果它在X秒内不返回答案,则该调用将被中止.
我知道使用timeout
的2011 Matlab版本是可能的,但是我有2010版本的Matlab.仍然可以限制函数的执行时间吗?
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?
推荐答案
正如其他人指出的那样,您不能在Matlab中本地执行此操作.但是在Unix系统上在Linux或Solaris上,我以前曾使用过一些肮脏的技巧来达到预期的效果.
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.
与其将您的.m文件作为带有参数的函数来调用,不如将所有参数数据保存到.mat文件中并编写一个shell命令来调用Matlab并运行您的.m文件,例如myfunc.m作为独立的例程,例如
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"
这会将myfunc.m限制为3秒的CPU执行时间.请注意,CPU不包括任何磁盘访问等.如果您需要其他一些行为,则可以将其他标志传递给ulimit.
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.
在myfunc.m中,您必须保存数据myfunc.m要返回到.mat文件,然后再次将其加载到调用程序中.有点讨厌,但我已经对其进行了测试,并且可以正常工作.注意内部ulimit命令使用bash shell.
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.
这篇关于Matlab函数执行的时间限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!