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

Hey folks, how do I calculate the current CPU usage in %? I looked at the source of htop, but as it is in C, I got lost backtracking where the numbers come from.

I also looked on CPAN, but I didn't find anything useful. If you did find a module that solves my problem exactly, tell me the name and which search terms you used.

  • Comment on How do I calculate the current CPU usage?

Replies are listed 'Best First'.
Re: How do I calculate the current CPU usage?
by Joost (Canon) on Jun 21, 2007 at 01:51 UTC
      This is not helpful. In the documentation it says the values are for one, five and fifteen minutes ago. I specifically asked for the current CPU usage.

      It is not clear what you mean with »"real" CPU load«. That which I am talking about is on a smooth scale between 0% and 100%.

        How do I calculate the current CPU usage on the Windows XP SP2 machine using Perl?
Re: How do I calculate the current CPU usage?
by andreas1234567 (Vicar) on Jun 21, 2007 at 05:55 UTC
    You did not mention your platform. vmstat reports (amongst other things) percentages of total CPU time:
    • us: Time spent running non-kernel code. (user time, including nice time)
    • sy: Time spent running kernel code. (system time)
    • id: Time spent idle. Prior to Linux 2.5.41, this includes IO-wait time.
    • wa: Time spent waiting for IO. Prior to Linux 2.5.41, shown as zero.
    $ vmstat -n 1 procs -----------memory---------- ---swap-- -----io---- --system-- --- +-cpu---- r b swpd free buff cache si so bi bo in cs us +sy id wa 1 0 160 84600 330848 251724 0 0 74 102 1 0 8 + 2 90 0 0 0 160 84600 330848 251724 0 0 0 0 1018 337 1 + 0 99 0 0 0 160 84600 330848 251724 0 0 0 160 1011 343 3 + 0 97 0 0 0 160 84600 330848 251724 0 0 0 0 1019 351 1 + 0 99 0 0 0 160 84608 330848 251724 0 0 0 0 1003 344 2 + 0 98 0
    --
    print map{chr}unpack(q{A3}x24,q{074117115116032097110111116104101114032080101114108032104097099107101114})
      This is close enough to what I needed. Thanks!
Re: How do I calculate the current CPU usage?
by sago (Scribe) on Jun 21, 2007 at 02:03 UTC
    Try to use this below command in the perl script. I tried this in linux/unix OS.

    Unix Command
    $ grep "model name" /proc/cpuinfo
    Output:
    model name : Intel(R) Xeon(TM) MP CPU 2.50GHz
      I did not want to know the model name or supposed clock frequency. None of the numbers in /proc/cpuinfo give the current CPU usage.