如果我有一个条件,把它放在应用函数内部/外部是否会显着影响运行时,例如:
names = c("Joe", "Jen", "Bob")
if("Joe" %in% names){
lapply(1:1000000, function(y){
#Do something computationally intensive
})
}
if("Jen" %in% names){
lapply(1:1000000, function(y){
#Do something computationally intensive
})
}
对:
lapply(1:1000000, function(y){
if("Joe" %in% names){
#Do something computationally intensive
}
if("Jen" %in% names){
#Do something computationally intensive
}
})
谢谢
循环中的if
非常昂贵。
使用 rbenchmark 查看。 将第一个写为函数 'a',第二个写成函数 'b',得到这个:
> benchmark(a(), b(), replications=1)
test replications elapsed relative user.self sys.self user.child sys.child
1 a() 1 0.595 1.00 0.593 0.000 0 0
2 b() 1 4.141 6.96 4.121 0.001 0 0
建议将"Joe"和"Jen"都放在名字中。 结果大致相同。
> benchmark(a(), b(), replications=1)
test replications elapsed relative user.self sys.self user.child sys.child
1 a() 1 0.600 1.000 0.597 0 0 0
2 b() 1 4.036 6.727 4.016 0 0 0
编辑:请注意,您提供给benchmark
的表达式是在计时循环中计算的,因此必须提供函数括号。