如何在R语言中为优化算法循环添加超时终止条件?
如何给优化算法循环添加5秒自动终止条件?
嘿,你的思路方向是对的,但直接用while(sys.time() < 3)会有问题——因为Sys.time()返回的是POSIXct类型的时间对象,和数值3没法直接比较,得换个更稳妥的方式来实现5秒终止的需求。
我来给你调整一下代码,核心是先记录循环开始的时间,然后每次循环检查当前时间与起始时间的差值是否小于5秒,同时保留你原来的迭代终止条件:
currIter <- 0 finished <- FALSE x_old <- x start_time <- Sys.time() # 新增:记录循环开始时间 while(finished == FALSE & difftime(Sys.time(), start_time, units = "secs") < 5){ # 修改循环条件,加入时间限制 StartT <- Sys.time() x_new <- lineSearch(f, x_old, x_old - a*numGradient(f, x_old, 10^-6), 10) if(currIter <= maxIter & abs(f(x_new)-f(x_old))>e & f(x_new)<f(x_old)){ x_old <- x_new result$x_opt <- x_new result$f_opt <- f(x_new) result$x_hist <- rbind(result$x_hist, x_new) result$f_hist <- rbind(result$f_hist, f(x_new)) result$iter <- currIter result$tEval <- rbind(result$tEval, Sys.time() - StartT) }else{ finished <- TRUE } currIter <- currIter + 1 } return(result) }
关键改动说明:
- 新增
start_time <- Sys.time():在循环启动前固定起始时间,避免每次循环重新计时导致误差 - 修改while循环条件:
finished == FALSE & difftime(Sys.time(), start_time, units = "secs") < 5,意思是只要还没触发原来的终止条件,并且运行时间还没到5秒,就继续循环 - 使用
difftime()计算时间差:这个函数会返回以秒为单位的时间差值,能和数值5直接比较,避免类型不匹配的错误
这样修改后,你的循环会在两种情况下自动停止:要么触发了你原来设置的迭代次数/函数收敛条件,要么运行时间达到5秒,完美满足你的需求。
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

