gpt4 book ai didi

r - 在循环中放置 Sys.sleep 的不同值,多个时间值

转载 作者:行者123 更新时间:2023-12-01 23:58:06 26 4
gpt4 key购买 nike

我有一个代码,并且在其中使用了一个循环,现在我希望该循环在完成一个查询后停止一小段时间。但是当这个循环执行下一个查询时,我希望它停止不同的时间间隔。例如第一次查询后 - 10 秒第二次查询后 - 15 秒等等..

下面是循环

for (i in 1:nrow(uniquemail)) {
k <- 2
test3 <- subset(finaltest, finaltest$Email == uniquemail[i,1])
for (j in 1:nrow(test3)) {

uniquemail[i,k] <- test3[j,2]
uniquemail[i,k+1] <- as.character(test3[j,3])
uniquemail[i,k+2] <- as.numeric(test3[j,4])
uniquemail[i,k+3] <- as.numeric(test3[j,5])

k <- k+4

print(paste(i,j,k))
}
}

有什么办法可以完成这个任务吗?我使用了 Sys.sleep 但不知道如何将它用于我的上述动机。

最佳答案

如果您想为每次迭代创建一个 sleep 循环,并在操作之前开始计时 sleep 持续时间,并将每个循环增加 5 秒的 sleep 时间,您可以使用以下代码:见下文:

for (j in 1:3) {
tm <- proc.time() #take timing before your action

#do your things here
#
#

tmdiff <-(5 * j) - (proc.time()[3] - tm[3]) #you want to wait 5 seconds the first time,
#10 sec the second time, 15 sec the third time etc..

if (tmdiff > 0) {
#depending of how long your "thing" took,
print(paste("sleep for", tmdiff, "seconds"))#you are taking the difference from the start to end of "actions" and sleeping for that time
Sys.sleep(tmdiff)
}
}

如果您想在您的操作之后开始 sleep 持续时间:

for (j in 1:3) {    
#do your things here
#
#
tmsleep<-(5 * j) #you want to wait 5 seconds the first time,
#10 sec the second time, 15 sec the third time etc..
print(paste("sleep for", tmsleep, "seconds"))
Sys.sleep(tmsleep)
}
}

由于我们没有关于您的问题的任何进一步信息(也没有可重现的代码),我假设您遇到了重载某些类型的 API 和/或网页抓取的问题。如果是这样,我宁愿从选定的值范围内采样我的 sleep 时间,例如:

tmsleep<-sample(5:15,1)
Sys.sleep(tmsleep)

即 sleep 时间为 5 到 15 秒之间的值。另外,如果您想要有一个可预测的 sleep 时间,您可以使用 set.seed(j) ,其中 j 是循环变量:

set.seed(j)
tmsleep<-sample(5:15,1)
Sys.sleep(tmsleep)

关于r - 在循环中放置 Sys.sleep 的不同值,多个时间值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39220840/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com