在R中,为什么system.time不会在循环中工作



我想测量事情求和需要多长时间,并比较要添加的事物数量如何改变时间。例如,我想查看有 1、2 或 3 个数字求和的时间。

for (j in 1:3)
  print(j)
  user_time <- system.time(my_sum_func(j))[1]
  print(user_time)

我希望得到如下输出:

> for (j in 1:3)
+   print(j)
[1] 1
>   user_time <- system.time(my_sum_func(j))[1]
>   print(user_time)
user.self 
        0 #or some  other time
+   print(j)
[1] 2
>   user_time <- system.time(my_sum_func(j))[1]
>   print(user_time)
user.self 
        0 #or some  other time
+   print(j)
[1] 3
>   user_time <- system.time(my_sum_func(j))[1]
>   print(user_time)
user.self 
        0 #or some  other time

但相反,我实际上得到了:

> for (j in 1:3)
+   print(j)
[1] 1
[1] 2
[1] 3
>   user_time <- system.time(my_sum_func(j))[1]
>   print(user_time)
user.self 
        0 

系统时间似乎只在循环的最后一次迭代上运行。

如何获取每个不同测试的用户时间?

您在每次迭代时都会覆盖user_time。改为创建一个列表,并在循环期间附加值。接下来,您可以比较时间或根据需要求和它们

user_time <- list()
for (j in 1:3) {
...
user_time[[(length(user_time) + 1)]] <- system.time(my_sum_func(j))
...
}

最新更新