我试图测试这两个函数中的哪一个在计算组合或排列的总和时更快。
更新:Option Explicit
Sub ReturnActions()
Dim itemnumber As String
Dim finalrow As Integer
Dim i As Integer
Sheet1.Range("B35:N100").ClearContents
itemnumber = Sheet1.Range("E8").Value
finalrow = Sheet3.Range("G10").End(xlUp).Row
Worksheets("Total List").Activate
For i = 2 To finalrow
If Cells(i, 7) = itemnumber Then
Sheet3.Range(Cells(i, 7), Cells(i, 12)).Copy
Sheet1.Range("B50").End(xlUp).Offset(1, 0).PasteSpecial xlPasteFormulasAndNumberFormats
End If
Next i
Worksheets("Action Entry").Activate
Range("E8").Select
End Sub
包似乎是我原始问题的答案,但我想知道为什么microbenchmark
中的切换比combo_beast
便宜...
combo_unicorn
第一个函数使用嵌套开关:
> microbenchmark(combo_beast(5,'yes','yes'))
Unit: microseconds
expr min lq mean median uq max neval
combo_beast(5, "yes", "yes") 8.019 8.354 9.94767 8.688 9.022 32.412 100
> microbenchmark(combo_unicorn(5,'yes','yes'))
Unit: microseconds
expr min lq mean median uq max neval
combo_unicorn(5, "yes", "yes") 8.354 8.688 10.63269 9.022 9.357 41.768 100
第二个功能使用if / else if方法:
combo_beast <- function(n, order, rep){
switch(order,
yes = switch(rep,
yes = {
y <- 0
for(i in 1:n){
x <- n^i
y <- x + y}
return(y)
},
no = {
y <- 0
for(i in 1:n){
x <- factorial(n + i - 1)/(factorial(i)*factorial(n-1))
y <- x + y}
return(y)
}
),
no = switch(rep,
yes = {
y <- 0
for(i in 1:n){
x <- factorial(n)/(factorial(n - i))
y <- x + y}
return(y)
},
no = {
y <- 0
for(i in 1:n){
x <- factorial(n)/(factorial(n-i)*factorial(i))
y <- x + y}
return(y)
}
)
)
}
我已尝试将combo_unicorn <- function(n, order, rep){
if(order == 'yes' & rep == 'yes'){
y <- 0
for(i in 1:n){
x <- n^i
y <- x + y}
return(y)
} else if (order == 'yes' & rep == 'no'){
y <- 0
for(i in 1:n){
x <- factorial(n + i - 1)/(factorial(i)*factorial(n-1))
y <- x + y}
return(y)
} else if (order == 'no' & rep == 'no'){
y <- 0
for(i in 1:n){
x <- factorial(n)/(factorial(n-i)*factorial(i))
y <- x + y}
return(y)
} else {
y <- 0
for(i in 1:n){
x <- factorial(n)/(factorial(n - i))
y <- x + y}
return(y)
}
}
放在任一函数的开头,并在最后添加ptm <- proc.time()
,但无论我做多大proc.time() - ptm
,它都会保持返回0。