提问人:sankha 提问时间:7/19/2023 最后编辑:zx8754sankha 更新时间:7/19/2023 访问量:46
了解和比较各种计算的执行时间
Understanding and comparing execution times of various computations
问:
在第一个比较中,与 相比,具有更好的平均时序。为什么会这样?
r sqrt(5)^2
r sqrt(5^2)
在第二次比较中,上述情况正好相反。我已经尝试了更多的迭代次数(次数)。 发现很难理解发生了什么。
microbenchmark::microbenchmark(sqrt(5)^2,sqrt(5^2), times = 1e3)
#> Unit: nanoseconds
#> expr min lq mean median uq max neval cld
#> sqrt(5)^2 144 151 210.705 162 169 6304 1000 a
#> sqrt(5^2) 148 157 269.604 169 226 25936 1000 b
microbenchmark::microbenchmark(sqrt(5)^2,sqrt(5^2), log(exp(5)), times = 1e3)
#> Unit: nanoseconds
#> expr min lq mean median uq max neval cld
#> sqrt(5)^2 145 168 193.956 180 184 3059 1000 a
#> sqrt(5^2) 149 159 189.753 170 176 3778 1000 a
#> log(exp(5)) 132 147 183.599 154 166 8062 1000 a
创建于 2023-07-19 由 reprex 软件包 (v2.0.1)
答:
2赞
zx8754
7/19/2023
#1
与一个输入进行比较没有多大意义 - 5。尝试更长的向量。我们可以看到中位数是一致的。
x <- 1:10000
microbenchmark::microbenchmark(sqrt(x)^2, sqrt(x^2), times = 10000)
# Unit: microseconds
# expr min lq mean median uq max neval cld
# sqrt(x)^2 29.0 51.6 95.77408 54.9 58.3 79210.8 10000 a
# sqrt(x^2) 35.4 47.0 61.64323 48.8 52.0 8017.2 10000 b
microbenchmark::microbenchmark(sqrt(x)^2, sqrt(x^2), log(exp(x)), times = 10000)
# Unit: microseconds
# expr min lq mean median uq max neval cld
# sqrt(x)^2 28.2 52.25 100.85237 56.1 60.4 80131.9 10000 a
# sqrt(x^2) 35.4 47.70 57.88721 49.7 53.5 4441.1 10000 a
# log(exp(x)) 162.1 196.90 262.39865 202.4 220.5 83254.2 10000 b
0赞
Marcello Zago
7/19/2023
#2
我认为仅仅看平均值是不够的。平均值容易出现异常值,当您查看最大值时,您肯定会有异常值。在这里,您会看到,对于两个表达式中的一个表达式,您始终具有非常大的值。这最终扭曲了均值。
就异常值而言,中位数更稳定。就像,@zx8754说:价值观更加一致。
评论
sqrt(x) takes less time compared to sqrt(y) where y>x
set.seed(1); x <- sample(1:10, 10000, replace = TRUE); y <- sample(101:110, 10000, replace = TRUE)