让我说下面的函数(仅作为示例,我的实际R计算中还有其他有意义的函数)
library(R.utils)
My_Fn = function() {
Some_Try =
try({
withTimeout({
Sys.sleep(30)
}, timeout = 10, onTimeout = "error")
}, silent = TRUE)
if (class(Some_Try) == 'try-error') {
XXX = 2
} else {
XXX = 3
}
return(XXX)
}
当我评估此功能时,我希望该功能在10秒钟内被强制停止。但在我的情况下却没有发生,仅在30秒后停止,如下所示-
> system.time(My_Fn())
user system elapsed
0.033 0.015 30.029
您能帮我弄清楚如何使我的功能在10秒钟后停止吗?
请在下面找到我的会话信息-
> sessionInfo()
R version 3.6.1 (2019-07-05)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 18.04.3 LTS
Matrix products: default
BLAS: /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.7.1
LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.7.1
locale:
[1] LC_CTYPE=C.UTF-8 LC_NUMERIC=C LC_TIME=C.UTF-8
[4] LC_COLLATE=C.UTF-8 LC_MONETARY=C.UTF-8 LC_MESSAGES=C.UTF-8
[7] LC_PAPER=C.UTF-8 LC_NAME=C LC_ADDRESS=C
[10] LC_TELEPHONE=C LC_MEASUREMENT=C.UTF-8 LC_IDENTIFICATION=C
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] R.utils_2.9.1 R.oo_1.23.0 R.methodsS3_1.7.1
loaded via a namespace (and not attached):
[1] compiler_3.6.1
当我查看与withTimeout()
函数相关的示例时,我发现了奇怪的行为-
下面的内容将在大约1秒内停止播放
foo <- function() {
print("Tic")
for (kk in 1:100) {
print(kk)
Sys.sleep(0.1)
}
print("Tac")
}
system.time({
tryCatch({
res <- withTimeout({
foo()
}, timeout = 1.08)
}, TimeoutException = function(ex) {
message("Timeout. Skipping.")
})
})
但是,下面仅在10秒内停止显示
foo <- function() {
print("Tic")
for (kk in 1:100) {
print(kk)
Sys.sleep(10.1)
}
print("Tac")
}
system.time({
tryCatch({
res <- withTimeout({
foo()
}, timeout = 1.08)
}, TimeoutException = function(ex) {
message("Timeout. Skipping.")
})
})
我希望上述两个示例都将在〜1.1秒后停止,这由参数timeout = 1.08
定义。那么,为什么会有所不同呢? withTimeout()
函数中是否存在任何错误?