stvn has asked for the wisdom of the Perl Monks concerning the following question:

Does anyone know of a reasonably system independent way of getting CPU usage information in Perl? I looked at GTop, but had some issues compiling libgtop (I am on Mac OS X). Before I start trying to tackle these issues though, I thought I should ask the monastary for suggestions. Basically I am looking for a minimum of CPU load percentage, but the more info the better. I would even be open to UNIX shell commands (preferably simpler than top)whose output I can parse as it is unlikely this will ever need to run on Windows (at least for now of course).

-stvn

Replies are listed 'Best First'.
Re: Finding out Processor Usage
by saintmike (Vicar) on Apr 10, 2004 at 23:38 UTC
    On Linux, the sysinfo() call can be used to obtain 1, 5 and 15 minute processor usage averages. While not available in the perl core, you can access it by writing a XS wrapper, or, even easier, use Inline::C:

    use warnings; use strict; use Inline "C"; my $one_minute_avg = one_minute_avg(); printf "Load avg: $one_minute_avg\n"; __END__ __C__ #include <sys/sysinfo.h> long one_minute_avg() { struct sysinfo si; if(sysinfo(&si) == 0) { return si.loads[0]; } else { return -1L; } }

    For the XS version and some more info (provided you don't mind it's in German), check out this article. The numbers returned are longs, not sure how they relate to what uptime is returning.

    Oh, and the /proc/loadavg pseudo file shows the load average on Linux also, as in

    0.63 0.65 0.79 1/112 6661
Re: Finding out Processor Usage
by eXile (Priest) on Apr 11, 2004 at 03:28 UTC
    Hi, I was just thinking what a nice module to write. What should I name it? Did a search on 'System' in CPAN and found these modules: Sys::CpuLoad, Sys::Load and System::Index (for a moment I'll not distinguish between CPU usage and 'load').
    System Index has an original approach of having some fixed functions by which an index for memory, CPU and disk-usage is calculated. This might tell you more than CPU-usage or load (I'm presuming here you want to know more about system performance, not only CPU-usage). I've seen machines with loads over 200 that had no performance problems (lots of processes in the run-queue that only needed a short slice of processor time). CPU usage will tell you something about CPU usage (duh), I mainly use that to estimate if the CPU is a bottleneck (if usage is >80% most of the time).
    My point: If somebody is 2.20 meters long that is an indication that he/she might be a good basketball player, but you have to take into account a lot more then heigth alone.

    update: fixed the System::Index link, I can't find it via search.cpan.org, only via kobesearch.cpan.org
Re: Finding out Processor Usage
by kvale (Monsignor) on Apr 10, 2004 at 22:48 UTC
    uptime is reasonably portable across Unices and is simple to parse:
    my $info = `uptime`; ($avg_1, $avg_5, $avg_15) = $info =~ /load average:\s+(\S+),\s+(\S+),\ +s+(\S+)/; print "$avg_1, $avg_5, $avg_15\n";

    -Mark

      I looked at uptime, but i wasnt sure how its output relates to CPU percentage, like which is output by top. Do you have any insight into this? Thanks.

      -stvn

        uptime is the same as the first line of top(1) or w(1). Load average however (which is what is reported there) is not CPU usage. Load average is the average number of processes *waiting to run/running* over the last x period. The higher the load average the greater the load on the system as the OS queues processes for a time slice. This has a vague relation to CPU usage but that is all. See this for more details.

        cheers

        tachyon

        uptime will output the current time, the time the system has been up, the number of users connected and the load averages. The load averages are a condensation of the %usr, %sys and %wio cpu statistics at that given time. Where usr and sys represent the % cpu cycles dealing with user and system calls respectively and wio are the percentage of cycles that are bound on io waits.
Re: Finding out Processor Usage
by insensate (Hermit) on Apr 11, 2004 at 00:11 UTC
    Monks, correct me if I have platform tunnel vision, but on both my AIX machine and my sun machine I use sar -uto output cpu utilization stats. Very easy to parse. For instance: sar -u 1 10 gives me 10 polls of my cpu utilization (usr, sys, wio and idle) at 1 second intervals, the -o flag lets me specify a file (in binary) to output the stats to, then running sar -f on that file lets me extract the stats. I've heard that on linux the systat package (http://perso.wanadoo.fr/sebastien.godard/) will let you use sar as well.
Re: Finding out Processor Usage
by sgifford (Prior) on Apr 10, 2004 at 22:50 UTC

    It seems like there should be a CPAN module to do this, but I just searched for one and nothing useful came up.

    top -b -n 1 -p 1 should be pretty easy to parse. Or vmstat, which displays how busy a CPU is. uptime is also available on all Unix systems I'm aware of, but the information it gives is somewhat limited.

      I agree, one would think there would be something on CPAN, but I must have looked for about 2 hours today and found nothing (except GTop).

      My version of top does not seem to support those options. By any chance do you know what they stand for, maybe if i knew that i could discern the equivalents on my system (Mac OS 10.3.3). Thanks.

      -stvn
        From my manpage:
        COMMAND-LINE OPTIONS ... b Batch mode. Useful for sending output from top to other programs or to a file. In this mode, top will not accept command line input. It runs until it pro­ duces the number of iterations requested with the n option or until killed. Output is plain text suitable for display on a dumb terminal. ... n Number of iterations. Update the display this number of times and then exit. ... p Monitor only processes with given process id. This flag can be given up to twenty times. This option is neither available interactively nor can it be put into the configuration file.
Re: Finding out Processor Usage
by Joost (Canon) on Apr 11, 2004 at 09:20 UTC
    If I want to check cpu usage and related info quitly, I go for vmstat, which will give you, amongst other info, the % idle, system and user time, or vmstat 1 which will do the same, but polls every second.

    The output of vmstat should not be difficult to parse, though I don't know if it's available everywhere (or gives output in the same format).

    One thing to watch out for, though, is that AFAIK it can produce "counter intuitive" results (like a maximum of 50% in fairly common cases) when you have intel hyper-threading cpu's.

    HTH,
    Joost.

Re: Finding out Processor Usage
by logan (Curate) on Apr 11, 2004 at 18:58 UTC
    Your best bet is sar. It's available for Linux, Solaris, Irix, HP-UX, AIX, the dreaded SCO, and probably more *nix. Sar comes with a ton of options for customizing output, so it's my main tool for measuring system performance. I wrote my own wrapper for parsing out only what I needed using a simple split (sorry, work won't let me share), then I printed everything to a file as comma-separated values, making it easy to process the data into reports, graphs, what have you. There's also a good article (code included) here about using Gnuplot to generate graphs from sar output.

    -Logan
    "What do I want? I'm an American. I want more."

Re: Finding out Processor Usage
by Anonymous Monk on Apr 14, 2004 at 06:41 UTC