From: Ross Bamford Date: 2006-01-11T08:28:04+09:00 Subject: Re: Finding CPU% of a linux task On Tue, 10 Jan 2006 22:59:27 -0000, Joe Van Dyk wrote: > On 1/10/06, Barbier de Reuille Pierre wrote: >> Well, on Linux 2.6, the list of the threads is in : >> >> /proc/[pid]/task >> >> But it is not true for Linux 2.4 :( >> And on 2.4, I really don't know if you can tell a process from a thread >> from the exterior. At least, I see no difference in the /proc virtual >> system. > > For my purposes, I don't want to make a distinction between threads > and processes. I just want an accurate cpu percentage of a running > program (which includes all of its threads and child processes). > Since you're looking in /proc anyway I guess this is for unixy systems, so _maybe_ the following is of use? module Process class << self def cpu_percent(pid) pgid = getpgid(pid) ps = `ps -Ao pcpu,pgrp`.to_a (ps[1..-1]).inject(0.0) do |sum,s| if s =~ /([\d.]+)\s*([\d]+)/ tcpu, tpgid = $~.captures (tpgid.to_i == pgid) ? sum + tcpu.to_f: sum end end end end end pid = (ARGV[0] || Process.pid).to_i puts "#{pid}: #{Process.cpu_percent(pid)}" Not a particularly clean one but maybe it gives a starting point? On my system a quick test gives: $ ps -o cmd,pcpu,pid,pgrp,sid CMD %CPU PID PGRP SID bash 0.0 4540 4540 4540 ruby -e fork { loop do 1000 2.2 4942 4942 4540 ruby -e fork { loop do 1000 4.3 4943 4942 4540 ps -o cmd,pcpu,pid,pgrp,sid 0.0 5393 5393 4540 $ ruby pinfo.rb 4942 4942: 6.5% $ ruby pinfo.rb 4294 pinfo.rb:4:in `getpgid': No such process (Errno::ESRCH) from pinfo.rb:4:in `cpu_percent' from pinfo.rb:17 (that second one is a deliberate example :) ) Check out 'man ps' for the different args etc, and the proper output format syntax if you're on non-GNU. -- Ross Bamford - rosco@roscopeco.remove.co.uk