计算循环中的计算数

时间:2018-06-14 15:44:58

标签: r

我有一个嵌套循环的大型数据集。我能够计算出计算机完成循环所需的时间。我也很好奇在循环中进行的计算次数。是否有一种简单的方法(比如system.time函数来计算使用的时间)来计算整个循环中的计算总数?

以下是样本数据

test = data.frame(ID = c(1,2,3), s= c(0.4,0.3,0.3), j1 = c(0.3,0.22,0.15), j2 = c(0.11,0.3,0.2))

以下是循环:

j = 1
k = 1

firstsum = 0
tm1 <- system.time(
  while (j <= nrow(test)){
    while (k <= nrow(test)){
      if (k != j) {
        for (i in 3:4){
          normindator = 0
          denominator = 0

          normindator = normindator + (test[j,i] * test[k, i])
          denominator = denominator + test[j, i] * test[j, i]
          firstsum = firstsum + normindator/denominator * test[k, 2]

        }
      }
      k = k + 1
    }
    secondsum = 0
    secondsum = secondsum + firstsum * test[j,2]
    j = j + 1
    k = 1
  }
)

1 个答案:

答案 0 :(得分:0)

我只会单独指定它。检查我是否正确,但你可以做这样的事情,即使它不好。

test = data.frame(ID = c(1,2,3), s= c(0.4,0.3,0.3), j1 = c(0.3,0.22,0.15), j2 = c(0.11,0.3,0.2))

j = 1
k = 1
count <- 0
firstsum = 0
tm1 <- system.time(
  while (j <= nrow(test)){
    count <- count + 1
    while (k <= nrow(test)){
      if (k != j) {
        for (i in 3:4){
          normindator = 0
          denominator = 0

          normindator = normindator + (test[j,i] * test[k, i])
          denominator = denominator + test[j, i] * test[j, i]
          firstsum = firstsum + normindator/denominator * test[k, 2]
          count<- count + 1
        }
      }
      else{count<- count +1 }
      k = k + 1
    }
    secondsum = 0
    secondsum = secondsum + firstsum * test[j,2]
    j = j + 1
    k = 1
    count <- count +1
  }
)
tm1
count
# > tm1
# user  system elapsed 
# 0.02    0.00    0.02 
# > count
# [1] 21

我知道这不是一个好方法,但检查你的目的很快。 如果你想具体知道每个循环的数量,只需在每个循环中加入一个不同的计数器变量。干杯!