Average CPU since inception

From packets2photons
Jump to navigation Jump to search

The following is an awk program for calculating the CPU load since some starting point.

BEGIN {
  prev_total = 0
  prev_idle = 0
  total_addition = 0
  loop_total = 0
  #print "This should print the average since inception"
  while (getline < "/proc/stat") {
    close("/proc/stat")
    idle = $5
    total = 0
    loop_total = loop_total + 1
    for (i=2; i<=NF; i++)
      total += $i
    #print "total:"total
    current = (1-(idle-prev_idle)/(total-prev_total))*100
    #print "current:"current"%"
    total_addition += current
    #print "total_addition:"total_addition
    prev_idle = idle
    prev_total = total
    #print "loop_total:"loop_total
    average = total_addition / loop_total
    print "The program has been running for " loop_total " seconds. Avg load since inception is " average"%"
    system("sleep 1")
  }
}

You can run it with:

awk -f cpu.awk

The following code is an extension where the load since a bash command is executed, is tracked. In this case, the bash command is a wget.

BEGIN {
  prev_total = 0
  prev_idle = 0
  total_addition = 0
  loop_total = 0
  system("wget  https://mirror.aarnet.edu.au/pub/TED-talks/AaronHuey_2010X_480.mp4 &")
  #print "This should print the average since inception"
  do {
    getline < "/proc/stat"
    close("/proc/stat")
    #print dl
    idle = $5
    total = 0
    loop_total = loop_total + 1
    for (i=2; i<=NF; i++)
      total += $i
    #print "total:"total
    current = (1-(idle-prev_idle)/(total-prev_total))*100
    #print "current:"current"%"
    total_addition += current
    #print "total_addition:"total_addition
    prev_idle = idle
    prev_total = total
    #print "loop_total:"loop_total
    average = total_addition / loop_total
    print "The program has been running for " loop_total " seconds. Avg load since inception is " average"%"
    system("sleep 1")
    }
    while (system("pgrep wget") == true)
}