假设我有一组脚本,里面有以下内容:每个脚本打印到控制台'hello world'和脚本执行时间。
t0<- Sys.time()
print('hello world')
t1<- Sys.time()
time.taken<- round(as.numeric(t1-t0), 2)
time.taken
cat(paste("n[script1] -","Execution time: ", time.taken, "seconds"))
现在我正试图获得多个源的时间执行:
source("modules/script1.R")
source("modules/script2.R")
source("modules/script3.R")
source("modules/script4.R")
source("modules/script5.R")
source("modules/script6.R")
但是,这将分别在控制台中而不是在环境中打印每个脚本的执行时间,在R环境中得到这样的东西会很棒:
#script execution time
#1 2 seconds
#2 2 seconds
#3 2 seconds
#4 2 seconds
#5 2 seconds
#6 2 seconds
这可能吗?有哪些资源可用于这种处理?
您可以使用Windows上的parLapply
或parallel
包中的mclapply
来并行运行脚本。
将脚本中最后一个计算值传递给source
函数。
如果您确保脚本的最后一个值是它的执行时间,它将被lapply
作为list
返回:
library(parallel)
l <- 1:6
# Create script files
createscript <- function(numscript) {
cat('
t0<- Sys.time()
print("hello world")
Sys.sleep(runif(1))
t1<- Sys.time()
time.taken<- round(as.numeric(t1-t0), 2)
time.taken
print(paste("[script1] -","Execution time: ", time.taken, "seconds"))
data.frame(time.taken)'
,file =paste0("Script",numscript,".R") , append = F)
T
}
lapply(l,createscript)
# Scripts list
scripts <- paste0("Script",l,".R")
# Run scripts in parallel
cl <- makeCluster(getOption("cl.cores", detectCores() - 1))
result <- parLapply(cl, scripts,function(script) {source(script)$value})
do.call(rbind,result)
time.taken
1 0.87
2 0.51
3 0.61
4 0.38
5 0.37
6 0.91