R 如果表达式花费的时间太长,如何使用withTimeout函数中断表达式
如果计算时间太长,我想终止一些代码,也就是说,计算时间超过2秒。我正在尝试使用带超时的R 如果表达式花费的时间太长,如何使用withTimeout函数中断表达式,r,timeout,R,Timeout,如果计算时间太长,我想终止一些代码,也就是说,计算时间超过2秒。我正在尝试使用带超时的功能。阅读帮助中的示例,以下代码正在运行,我得到一个错误: foo <- function() { print("Tic") for (kk in 1:100) { print(kk) Sys.sleep(0.1) } print("Tac") } res <- withTimeout({foo()}, timeout = 2) foo示例rnorm是一个
功能。阅读帮助中的示例,以下代码正在运行,我得到一个错误:
foo <- function() {
print("Tic")
for (kk in 1:100) {
print(kk)
Sys.sleep(0.1)
}
print("Tac")
}
res <- withTimeout({foo()}, timeout = 2)
foo示例rnorm
是一个已知的“问题”,您可以在上找到它作为不受支持的案例
你可以通过这样做来完成这项工作
foo1 <- function(n = 1000000) {
ret <- rep(0, n);
for (kk in 1:n) ret[kk] <- rnorm(1);
ret;
}
# The following will time out after 2s
tryCatch( { res <- withTimeout( { foo1() },
timeout = 2) },
TimeoutException = function(ex) cat("Timed out\n"))
#Timed out
# Confirm that res is empty
res
#NULL
foo1谢谢,我正在尝试测试代码,我无法想象我在这个问题上遇到了什么困难!不客气@ciccioz;请考虑通过在答案旁边设置绿色复选标记来结束问题。
foo1 <- function(n = 1000000) {
ret <- rep(0, n);
for (kk in 1:n) ret[kk] <- rnorm(1);
ret;
}
# The following will time out after 2s
tryCatch( { res <- withTimeout( { foo1() },
timeout = 2) },
TimeoutException = function(ex) cat("Timed out\n"))
#Timed out
# Confirm that res is empty
res
#NULL