【发布时间】:2021-10-20 05:25:57
【问题描述】:
我知道这可能是一个简单的问题,但我正在努力学习和改进。当我尝试这段代码时,它给了我错误:“没有循环中断/下一个,跳转到顶层”。有人可以建议为什么并帮助我吗?非常感谢。
x_1 <- rnorm(100)
x_2 <- rnorm(10000)
x_3 <- rnorm(1000000)
to_evaluate <- list(x_1, x_2, x_3)
speed_test <- for (i in to_evaluate) {
microbenchmark(mean_loop(i), mean_mat(i), mean(i))
}
print(speed_test)
mean_loop 和 mean_mat 的代码:
x <- c(1:11)
mean_loop <- function(x) {
sum_of_x <- 0
for(i in x){
sum_of_x <- sum_of_x + x[i]
}
mean_of_x <- sum_of_x/length(x)
return(mean_of_x)
}
mean_mat <- function(x) {
sum(diag(length(x))%*%x)/length(x)
}
函数microbenchmark(来自包microbenchmark)可让您测量代码运行的速度。如果你给它代码来评估,它会评估它 100 次,并返回关于代码运行多长时间的摘要统计信息。如果你给它多个表达式,它会对每个表达式都这样做。
【问题讨论】:
-
也许可以尝试使用
for (i in length(to_evaluate)。另外,您是否考虑过使用lapply?即lapply(to_evaluate, function(x) microbenchmark(mean_loop(x), mean_mat(x), mean(x)))?您能否添加用于microbenchmark()、mean_loop()和mean_mat()函数的包? -
谢谢!我添加了代码。不幸的是,您的解决方案都不适合我,但感谢您的帮助!
标签: r loops break next microbenchmark