Detect available and idle cores in R

Published by onesixx on

https://stackoverflow.com/questions/41024035/detect-available-and-idle-cores-in-r

library(parallel)
N_CORES <- detectCores()
CORES <- round(N_CORES*3/4)
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
})
Categories: R Basic

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x