Version 2 of Measuring your Application's CPU Utilization

Updated 2009-01-29 16:54:27 by LV

I've had occassion to provide CPU utilization feedback to the user. For instance, you might have a Tcl/Tk application that consumes lots of CPU cycles, but there are options which the user can implement to reduce the load. It's nice to provide direct feedback (without requiring the user to access a system utility). Your application might also manage other applications, in which you might need to know how those applications are consuming resources.

Although I first titled this Wiki page for CPU utilization, the following can also be applied to measuring memory usage, uptime, etc.

Problem How to determine CPU utilization for your running application.

Solution - UNIX Use ps. The Berkeley version of ps (Linux default, /usr/ucb/ps for Solaris) provides this bit of information, which can be retrieved rather easily via exec. I'll use Solaris as my example, since that's what I'm most familiar with.

If you execute /usr/ucb/ps, you'll get two or more lines that look like this:

  USER       PID %CPU %MEM   SZ  RSS TT       S    START  TIME COMMAND
  mgbacke   5681  0.1  0.2 2440 1960 pts/6    S 10:31:36  0:0 /usr/bin/tcsh

More then likely, you'll get a lot of lines like this. What we really want is just the line associated with our application. To do this, give the ps command the u option, followed by the PID (Process ID) of the application:

  /usr/ucb/ps u 5681

which would return the output shown above.

To implement the above from within a Tcl application, you might implement a procedure such as this:

  proc getCPUutil { } {
      set result [exec /usr/ucb/ps u [pid]]
      set cpuUtil [lindex $result 13]
  }

You could also inline the code by doing everything on one line, but that's not by style:

  set CPU [lindex [exec /usr/ucb/ps u [pid]] 13]

Marty Backe


HP, IBM, etc., users, please confirm a suitable version of ps is available.


Solution - Windows

  package require twapi
  # Total CPU utilization
  set cpu_utilization [twapi::get_processor_info -processorutilization]
  # This process utilization
  set process_utilization [twapi::get_process_info [pid] -processorutilization]
  # This thread utilization
  set thread_utilization [twapi::get_thread_info [twapi::get_current_thread_id] -processorutilization]