【问题标题】:Detect available and idle cores in R检测 R 中的可用和空闲内核
【发布时间】:2016-12-07 17:46:29
【问题描述】:
我经常在R 中使用parallel::detectCores() 来获取主机上的CPU 内核数,用于并行计算。我想为我的计算计算 available 和 idle 核心的数量。如果其他用户正在使用某些内核,我不想为我的程序占用它们。有没有办法我们可以通过编程方式做到这一点?
【问题讨论】:
标签:
r
foreach
parallel-processing
multiprocessing
cpu-cores
【解决方案1】:
这是一种使用系统命令和正则表达式来获取每个处理器的空闲时间的方法......这可能应该扩展到一个带有选项的函数,以允许其他性能指标(即系统时间)。
library(doParallel)
# total cores
N_CORES <- detectCores()
# create list for readable lapply output
cores <- lapply(1:N_CORES, function(x) x - 1)
names(cores) <- paste0('CPU', 1:N_CORES - 1)
# use platform specific system commands to get idle time
proc_idle_time <- lapply(cores, function(x) {
if (.Platform$OS.type == 'windows') {
out <- system2(
command = 'typeperf',
args = c('-sc', 1, sprintf('"\\processor(%s)\\%% idle time"', x)),
stdout = TRUE)
idle_time <- strsplit(out[3], ',')[[1]][2]
idle_time <- as.numeric(gsub('[^0-9.]', '', idle_time))
} else {
# assumes linux
out <- system2(
command = 'mpstat',
args = c('-P', x),
stdout = TRUE)
idle_time <- as.numeric(unlist(strsplit(out[4], ' {2,}'))[12])
}
idle_time
})