首页 > 解决方案 > 如何在图中表示函数的效率

问题描述

在学校,我们正在学习使用 R,我们必须找到一种算法来以不同的方式计算排列的阶数。所以我想出了4种可以比较的不同算法。但是现在,我希望能够根据我们提供的数据大小显示每个函数的工作时间。

calculOrdrePermutation所以首先,我想在不改变数据大小的情况下显示至少一个函数(我称之为函数)的时间。这就是我所做的:

createProcessTest <- function(func, variables, numberOfTests) {
  outputProgress <- T
  ptm <- proc.time()
  times <- c()
  for(i in 1:numberOfTests) {
    func(variables)
    times <- append(times, (proc.time() - ptm)[3])
    if(outputProgress & i %% 5 == 0) {
      print(paste((i/numberOfTests) * 100, "%"))
    }
  }
  return(times)
}

sampleSize <- 100
nbOperations <- 100
extrait <- sample(1:sampleSize, sampleSize)
matriceDePermutation <- trouverMatriceDePermutation(extrait)

tempsRapideMatrice = createProcessTest(calculOrdrePermutation, matriceDePermutation, nbOperations)
plot(y=tempsRapideMatrice, x=1:nbOperations, cex=0.1, type="l", main="Using matrix", sub="sans boucle", ylab="Time (s)", xlab="Number of iterations")

阴谋 它看起来大致像这样

所以这还不错,我可以显示一个代表这个函数时间的图。但它当然是线性的,所以我们没有太多兴趣......

所以我开始创建一个函数,通过逐渐改变来完成这个过程sampleSize

doFullTest <- function(func, useMatrix, numberOfTestsPerN, maxN) {
  temps <- c()
  for(sampleSize in seq(from=1, to=maxN, by=1)) {
    permut <- sample(1:sampleSize, sampleSize)

    if(useMatrix) {
      permut <- trouverMatriceDePermutation(extrait)
    }

    temps <- append(temps, mean(createProcessTest(func, permut, numberOfTestsPerN)))
  }
  return(temps)
}

所以我可以这样使用它:

plot(x=1:100, y=doFullTest(calculOrdrePermutation, T, 5, 100), type="h")

直方图 使用的时间取决于数据的大小,从 N=1 到 N=100

所以我要求的是每个数据大小运行 5 次函数来取平均值,然后以增加的大小重复。但是正如你所看到的,不可能研究它,我希望有一个线性直方图(因为我的算法的复杂度为 O(n) )。

我的代码有问题吗?我做错了吗?

我很确定我离我的目标不远,但结果令人非常沮丧......

谢谢您的帮助!

标签: rplottime

解决方案


推荐阅读