# #——风格,回声= FALSE,结果= '飞机 '-------------------------------------------------------- 选项(宽度= 100)knitr: opts_chunk设置(eval = as.logical (Sys美元。采用“KNITR_EVAL”,“真正的”)),缓存= as.logical (Sys。getenv(“KNITR_CACHE”,“TRUE”))## ----设置,回声= FALSE ---------------------------------------------------------------------------- suppressPackageStartupMessages({库(BiocParallel)库(微基准测试 ) }) ## ---- vectorize ------------------------------------------------------------------------------------ x < - 1:10日志(x) # #不是(我在seq_along (x)) x[我]< -日志(x[我])# #——预先分配 --------------------------------------------------------------------------------- 结果< -数字(10)结果[1]< - runif(1)(我在2:长度(结果)结果[我]< - runif(1) *结果[i - 1]结果# #,效率低下 ---------------------------------------------------------------------------------- f0 < -函数(n,= 2) {# # stopifnot (is.integer (n) & &(长度(n) = = 1) & & # # ! is.na (n) & & (n > 0))结果< -数字()(我在seq_len (n))结果[[我]]< - *日志(i)的结果 } ## ---- 系统时间 ---------------------------------------------------------------------------------- system.time (f0 (10000) n < - 1000 * seq (1,, 2) t < -酸式焦磷酸钠(n,函数(我)system.time (f0(我)[[3]])情节(t ~ n, type = " b ") ## ---- correct-init --------------------------------------------------------------------------------- n < - 10000系统。预计时间(< - f0 (n))(预期)# #——葫芦 ---------------------------------------------------------------------------------------- f1 < -函数(n = 2){结果< -数字()(我在seq_len (n))结果[[我]]< -日志(i)} *结果相同的(预期,f1 (n))库(微基准测试)微基准测试(f0 (n), f1 (n),* = 5) # #——preallocate-and-fill ------------------------------------------------------------------------- f2 < -函数(n = 2){结果< -数字(n)(我在seq_len (n))结果[[我]]< -日志(i)} *结果相同的(预期,f2 (n))微基准测试(f0 (n), f2 (n),* = 5) # #——use-apply ------------------------------------------------------------------------------------ f3 < -函数(n = 2) *酸式焦磷酸钠(seq_len (n),日志)相同(预期,f3 (n))微基准测试(f0 (n), f2 (n), f3 (n),* = 10) # #——use-vectorize -------------------------------------------------------------------------------- f4 < -函数(n = 2) *日志(seq_len (n))相同(预期,f4 (n))微基准测试(f0 (n), f3 (n), f4 (n),* = 10) # #——vectorized-scale ----------------------------------------------------------------------------- n < - 10 ^ (8) # 100 x大于f0 t < -酸式焦磷酸钠(n,函数(i) system.time (f4 (i))[[3]])情节(t ~ n, log =“xy”, type="b") ## ----parallel-sleep------------------------------------------------------------------------------- library(BiocParallel) fun <- function(i) { Sys.sleep(1) i } ## serial f0 <- function(n) lapply(seq_len(n), fun) ## parallel f1 <- function(n) bplapply(seq_len(n), fun)