首页 > 解决方案 > 如果时间过长,如何使用 withTimeout 函数中断表达式

问题描述

如果计算时间太长,我想终止一些代码,即,它需要超过 2 秒。我正在尝试使用该withTimeout功能。阅读帮助中的示例,以下代码正在运行,但出现错误:

foo <- function() {
    print("Tic")
    for (kk in 1:100) {
    print(kk)
    Sys.sleep(0.1)
    }
print("Tac")
}

res <- withTimeout({foo()}, timeout = 2)

我试图复制这个逻辑,编写以下代码,但它不起作用,即即使超时已经过去,计算也会结束(在我的笔记本电脑上,它大约需要 10 秒)。

res <- withTimeout({rnorm(100000000)}, timeout = 2)

有谁知道为什么?

标签: rtimeout

解决方案


rnorm示例是一个已知的“问题”,您可以在R.utilsGitHub 站点上找到它作为不受支持的案例。

可以通过做这项工作

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 

推荐阅读