Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an R function to log CPU usage?

Tags:

r

I want to run a code chunk and see how much of my CPU is being used. The equivalent of using task manager (activity monitor in mac), is there any R-way to achieve that?

like image 364
Angel F. Escalante Avatar asked Aug 31 '25 20:08

Angel F. Escalante


2 Answers

Perhaps you could make a system call, e.g.

cpu_log <- c()
for (i in seq(1, 1000, 1)) {
  print(i)
  cpu_log[[i]] <- system("ps -A -o %cpu | awk '{ cpu += $1} END {print cpu}' ", intern = TRUE)
}

plot(y = cpu_log, x = 1:1000)

example_1.png

like image 75
jared_mamrot Avatar answered Sep 03 '25 23:09

jared_mamrot


I don't know if this is the best way, but you can use proc.time(), which is part of base r.

ptm <- proc.time()

for (i in 1:1000) {rnorm(100000)}  #insert your code here

CPU_usage<-proc.time() - ptm      #compute the difference

CPU_usage

   user  system elapsed 
  6.407   0.385   6.896 

There is more written about user, sys, and elapsed time here.

like image 37
Joe Erinjeri Avatar answered Sep 04 '25 00:09

Joe Erinjeri