rcpucpu-usage

R: how to check how many cores/CPU usage available


R is single-threaded.

  1. Using R, how to check how many cores/threads are running R in Windows and Linux? (Or how many Rs are running)
  2. Using R, how to check the usage of each core that is running R in Windows and Linux? (Or the percentage of CPU each R is using)

For example, if I have two R opened running projects. I would expect that there are 2 threads running R with some % of CPU for each thread. Then I open another R. How to use the third R to check the number of threads (2 in this case) and percentage of CPU being used by R?


Solution

  • 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