我想对我正在调用的函数设置时间限制,这样如果它超时,它就会移动到脚本的下一部分(我正在运行source("..."))。该函数是使用 Rcpp 编写的,并且checkUserInterrupt();经常包含在整个过程中。我一直withTimeout在R.utils包中使用 option onTimeout = silent,但是超时仍然是暂停脚本的执行。
然后我在内部运行它tryCatch以NULL在出现任何错误的情况下返回,但它仍然停止我的脚本。我已经包含了一个复制这个问题的简短函数。
#include <Rcpp.h>
#include <chrono>
#include <thread>
using namespace Rcpp;
void sleep_fn(int n) // sleeps for n seconds
{
std::chrono::seconds dura( n );
std::this_thread::sleep_for( dura );
}
// [[Rcpp::export]]
int sleep_for(int n) // sleeps for n seconds and then returns n
{
for (int i = 0; i < n; i++)
{
checkUserInterrupt();
sleep_fn(1);
}
return(n);
}
Run Code Online (Sandbox Code Playgroud)
现在,为了进行比较,让我们运行它以及 R 命令 …