【问题标题】:How to print a variable inside a for loop to the console in real time as the loop is running?如何在循环运行时将for循环内的变量实时打印到控制台?
【发布时间】:2013-03-18 11:39:40
【问题描述】:

我有一个循环,每次迭代都需要很长时间,我想实时查看它的进度。当循环正在运行时,如何将 for 循环内的变量实时打印到控制台?这些中的每一个都会在循环完成后打印所有内容,这对我来说没用:

for(i in 1:10){
  write(i,stdout())
}

for(i in 1:10){
  write(i,stderr())
}

for(i in 1:10){
  print(i)
}
1
2
3
4
5
6
7
8
9
10

【问题讨论】:

    标签: r loops for-loop printing


    【解决方案1】:

    最后一个是实时打印的,试试这样:

    for(i in 1:10){
      Sys.sleep(0.1)
      print(i)
    }
    

    这在 Rstudio 中看起来不错,但在经典 Rgui 中,您必须单击控制台才能刷新(例如通过 Sys.sleep(0.5) 增加睡眠有助于看到这一点)。您可以通过使用清除缓冲区的flush.console 来规避这种情况:

    for(i in 1:10){
      Sys.sleep(0.1)
      print(i)
      flush.console() 
    }
    

    或者在 Windows 中,您可以在上方工具栏中选择 Misc 并取消选中 buffered output


    如果您的目标是跟踪循环的过程,那么当您运行大量迭代时,上述方法会感觉有点尴尬(至少在我看来)。在这种情况下,使用进度条可能会更好:

    n<- 1000
    pb <- txtProgressBar(min = 0, max = n, style = 3) #text based bar
    for(i in 1:n){
       Sys.sleep(0.001) 
       setTxtProgressBar(pb, i)
    }
    close(pb)
    

    或者更好的东西:

    library(tcltk)
    n<- 1000
    pb <- tkProgressBar(title = "Doing something", min = 0, max = n, width = 200)
    for(i in 1:n){
       Sys.sleep(0.001) 
       setTkProgressBar(pb, i, label=paste(round(i/n*100,1),"% done"))
    }
    close(pb)
    

    【讨论】:

    • 哎呀,做一个真实的例子可能是个好主意。感谢您清理一切。
    • 埃里克,检查我更新的答案,我添加了功能示例,使您成为一个很好的进度条。
    【解决方案2】:

    cat() 函数允许您编写有用的复杂语句来跟踪脚本的进度

    for(i in 1:10){
      ptm0 <- proc.time()
      Sys.sleep(0.5)  
      ptm1=proc.time() - ptm0
      jnk=as.numeric(ptm1[3])
      cat('\n','It took ', jnk, "seconds to do iteration", i)
    }
    
    >It took  0.49 seconds to do iteration 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-26
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 2016-01-10
      • 2021-09-24
      相关资源
      最近更新 更多