告诉循环在花费太长时间时"Skip"迭代

  • 本文关键字:长时间 Skip 迭代 循环 r
  • 更新时间 :
  • 英文 :


我在R:中有这个代码

output = list()
for (i in 1:999)
{tryCatch({
{
link_i <- paste0(www.some_website, i+1,  /some_extension/, i,  .com)
material_i <- fromJSON(link_i)
output[[i]] <- material_i
}
}, error = function(e){})
}

由于我正在运行的代码的性质,我注意到有时这个循环会";"卡住";在特定的迭代中。例如,这个循环可能在第45次迭代时被卡住,需要很长时间。

我正在寻找某种机制来告诉计算机";如果在某个迭代上花费的时间超过x秒,则跳到下一个迭代";。

我在这里发现了一个可能有用的函数:withTimeout:评估一个R表达式,如果它花费太长,就会中断它,但我不确定这是否是用于此类任务的正确函数。

可以推荐什么?我如何使用它?

您链接到的函数对我来说似乎很合适(但我从未使用过它(。这里有一个函数foo()的例子,除了x = 5需要5秒才能运行外,它对所有输入都很快。

suppressPackageStartupMessages(library(R.utils))
# function that is fast except when x = 5
foo <- function(x) {
if (x == 5) {
Sys.sleep(5)
} else {
Sys.sleep(0.5)
}
return(x)
}
# create a list to store the results
res <- vector("list", length = 10L)
# Make a loop where we try to store the result of each iteration. If iteration
# takes more than 1 sec, then skip it.
for (i in 1:10) {
print(i)
tryCatch({
res[[i]] <- withTimeout({
foo(i)
}, timeout = 1)
}, TimeoutException = function(ex) {
message("Timeout. Skipping.")
res[[i]] <- NULL
})
}
#> [1] 1
#> [1] 2
#> [1] 3
#> [1] 4
#> [1] 5
#> Timeout. Skipping.
#> [1] 6
#> [1] 7
#> [1] 8
#> [1] 9
#> [1] 10
res
#> [[1]]
#> [1] 1
#> 
#> [[2]]
#> [1] 2
#> 
#> [[3]]
#> [1] 3
#> 
#> [[4]]
#> [1] 4
#> 
#> [[5]]
#> NULL
#> 
#> [[6]]
#> [1] 6
#> 
#> [[7]]
#> [1] 7
#> 
#> [[8]]
#> [1] 8
#> 
#> [[9]]
#> [1] 9
#> 
#> [[10]]
#> [1] 10

创建于2022-09-16,reprex v2.0.2