f <- function(n){
s <- 0
for (i in 1:n){
s <- s + (i/2)
}
print(s)
}
Run Code Online (Sandbox Code Playgroud)
当然,棘手的部分是s递归地依赖于前一个循环.
[编辑]
谢谢您的回答.我只是试图使用R中的矢量化与循环相比来验证性能的增量.
具有n = 10亿以上函数采用287秒,同时兼具sum((1:n)/2)和 sum(seq_len(n)/2)返回我一个错误,该系统"不能分配大小7.5 GB的载体"
为了比较,Julia中的相同函数(n = 1000000000)需要38秒(0.87定义类型s),在C++中使用优化编译2.48秒/0.87,使用numba装饰器在Python 98秒/ 0.88中编译.
你可以这样做(以防万一n>0):
sum(seq_len(n)/2)
f(10)
#[1] 27.5
sum(seq_len(10)/2)
#[1] 27.5
Run Code Online (Sandbox Code Playgroud)
如果n<0:
sum((1:n)/2)
n <- -11
f(n)
#[1] -32.5
sum((1:n)/2)
#[1] -32.5
Run Code Online (Sandbox Code Playgroud)
只是一个快速的基准测试:
library(microbenchmark)
n <- 10000
f1 <- function(n) sum(seq_len(n)/2)
f2 <- function(n){ s <- 0;for (i in 1:n){s <- s + (i/2);};s}
f1(n)==f2(n)
# [1] TRUE
microbenchmark(f1(n), f2(n))
# Unit: microseconds
# expr min lq mean median uq max neval
# f1(n) 20.733 22.235 27.51751 22.836 24.639 82.028 100
# f2(n) 3971.008 4275.383 4517.52582 4484.510 4648.867 5867.272 100
Run Code Online (Sandbox Code Playgroud)