R: how to check how many cores/CPU usage available
Using R, how to check how many cores/threads are running R in Windows and Linux? (Or how many Rs are running)
One valid answer that I haven't read yet here is simply using the ps R package with the function ps()
you can then subset the table returned by processes with the name "rsession":
ps::ps()[ps::ps()$name == "rsession",]
Number of rows will give you the number of sessions existing on the computer/server:
nrow(ps::ps()[ps::ps()$name == "rsession",])
I am not entirely sure about what the function ps_num_threads()
does but it might also be interesting to check if the result make sense:
ps::ps_num_threads(ps::ps_handle())
I unfortunately did not found anything about %CPU usage in the ps R package but you can give a try to the function I quote in my other answer, it should work under Linux.
If you open multiple R windows, each window will be running on a different core up to the maximum number of cores that you have. This is automatically implemented on windows and mac computers. If you want to know how many cores you have, you can run:
library(parallel)
detectCores()
On Linux you can send ps command to the system: it gives you the average cpu usage and the memory usage of the program called rsession:
splitted <- strsplit(system("ps -C rsession -o %cpu,%mem,pid,cmd", intern = TRUE), " ")
df <- do.call(rbind, lapply(splitted[-1],
function(x) data.frame(
cpu = as.numeric(x[2]),
mem = as.numeric(x[4]),
pid = as.numeric(x[5]),
cmd = paste(x[-c(1:5)], collapse = " "))))
df
# cpu mem pid cmd
#1 0.8 0.7 11001 /usr/lib/rstudio/bin/rsession
#2 0.0 0.2 12397 /usr/lib/rstudio/bin/rsession
#3 0.1 0.7 14960 /usr/lib/rstudio/bin/rsession
#4 0.4 0.2 26122 /usr/lib/rstudio-server/bin/rsession
#5 0.3 8.3 35782 /usr/lib/rstudio/bin/rsession
You can probably improve it to get the parent id and the instantaneous CPU usage with other options passed to ps or top and deduce the number of cores used by each session.
On Windows you can try this:
a <- system("wmic path Win32_PerfFormattedData_PerfProc_Process get Name,PercentProcessorTime", intern = TRUE)
df <- do.call(rbind, lapply(strsplit(a, " "), function(x) {x <- x[x != ""];data.frame(process = x[1], cpu = x[2])}))
df[grepl("Rgui|rstudio", df$process),]
# process cpu
# 105 Rgui 0
# 108 rstudio 0