使用 microbenchmark 做基准测试
由于 Rcpp 的主要动机是提高性能,您需要能够准确测量代码的运行时间。为此,您将使用 microbenchmark 包中的 microbenchmark() 函数。
microbenchmark() 接受带名称的表达式作为参数,以随机顺序将每个表达式执行给定次数(默认 100 次),并返回一些汇总统计量。在本课程中,我们只关注 median 列。
工作区中已提供一个包含 100,000 个标准正态随机数的向量 x。
本练习是课程的一部分
用 Rcpp 优化 R 代码
练习说明
- 载入
microbenchmark包。 - 编写函数
sum_loop(),使用 R 的for循环计算向量中所有元素的总和。 - 使用
all.equal()函数验证其结果与sum()是否一致。 - 使用
microbenchmark()比较性能。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Load microbenchmark
___
# Define the function sum_loop
sum_loop <- function(x) {
result <- 0
___
result
}
# Check for equality
___(sum_loop(x), sum(x))
# Compare the performance
___(sum_loop = sum_loop(x), R_sum = sum(x))