r - 如果时间过长,如何使用 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)
有谁知道为什么?
解决方案
该rnorm
示例是一个已知的“问题”,您可以在R.utils
GitHub 站点上找到它作为不受支持的案例。
你可以通过做这项工作
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
推荐阅读
- unit-testing - 在没有杂乱的类型转换的情况下使用 jest.mock 和 TypeScript?
- c - C 编程 - 从 char * 转换为 char 数组?
- mongodb - 如何查询数组中的对象并返回一个对象?
- python - Python: def __init__(self, config_path: str, *args, **kwargs): ^ SyntaxError: invalid syntax
- angular - Angular 5 Firebase Auth Guard 登录状态与从 Auth 服务返回的不同
- angular - 如何减小 Angular 5 模板文件(component.html)的大小?
- javascript - Javascript - 数据重组所需的递归迭代器 - 很难嵌套
- httprequest - Http post and get request in angular 6
- hibernate - “字段列表”中的休眠 JPA 未知列
- sql - 从具有唯一值的列的联接表中选择最大日期