in reply to Calculating percent cpu in linux?

Well after a bit of work I have come up with the following:
use strict; require "asm/param.ph"; open UPTIME, "</proc/uptime"; my @up = split('\s+', <UPTIME>); close UPTIME; my $pid = shift or die "need pid"; open STAT, "</proc/$pid/stat"; my @stat = split('\s+', <STAT>); close STAT; my $total_time = $stat[13] + $stat[14]; my $include_dead_children = 1; if ($include_dead_children) { $total_time += $stat[15] + $stat[16]; } print $stat[21], "\n"; my $start_time = $stat[21]; my $seconds = $up[0] - $start_time / HZ(); my $pcpu; if($seconds) { $pcpu = ($total_time * 100 / HZ()) / $seconds; } print "start_time $start_time\n"; printf("%%CPU %2.2g\n", $pcpu);
By default this is including reaped children. I don't think ps does.

Update: fix to %CPU in printf per zentara.

-- gam3
A picture is worth a thousand words, but takes 200K.

Replies are listed 'Best First'.
Re^2: Calculating percent cpu in linux?
by zentara (Cardinal) on May 03, 2005 at 14:55 UTC
    A minor nitpick...Invalid conversion in printf: "%C" at ./cpu-usage

    But what I really wanted to say, is I often use a similar script I wrote called MeM. It pops up a Tk window in the upper left corner of the screen, and constantly updates and reports memory usage of a pid( or the calling script). Anyways, you could easily modify the code, to report cpu usage. Here is the code, just change it to run your code, and name it accordingly.

    package MeM; use warnings; use strict; use vars qw(@ISA @EXPORT_OK); @ISA = qw(Exporter); # inherit the import() from Exporter.pm @EXPORT_OK = qw(); # list of things to export if asked to my $pid =$$; if (fork() == 0) { require Tk; my $mw = new MainWindow; $mw->overrideredirect(1); my $t = $mw->Label(-text => '', -bg => 'black', -fg => 'yellow')-> +pack; $0 = 'MeM'; my $id = Tk::After->new($mw, 1000, 'repeat', [ \&refresh, $pid ]); Tk::MainLoop(); sub refresh { my $pid = shift; #asmutils version of cat my @size = split "\n", `/home/zentara/perl5lib/cat /proc/$pid/ +status`; #my @size = split "\n", `cat /proc/$pid/status`; (my $vmsize) = grep { /VmSize/ } @size; my (undef, $size) = split ' ', $vmsize; $t->configure(-text => "PID: $pid -> $size"); if ($size eq '') { exit } } } 1;

    I'm not really a human, but I play one on earth. flash japh
Re^2: Calculating percent cpu in linux?
by suaveant (Parson) on May 04, 2005 at 14:59 UTC
    Ahh.. that looks like it works.. thanks a lot!

                    - Ant
                    - Some of my best work - (1 2 3)