PHP: calculate percentage of CPU load


Read first: Function sys_getloadavg in PHP < 5.1.3

This function can calculate percentage of CPU load, work done with LINUX and WINDOWS OS.

<?
function _calc_CPU_Load()
{
    if (strncmp(PHP_OS, 'WIN', 3) == 0)
    {
        switch (PHP_VERSION)
        {
            case '5.0.0':
            case '5.0.1':
            case '5.0.2':
            case '5.0.3':
            case '4.3.10':
                return false;
                break;
        }

        @$com = new COM("WinMgmts:{impersonationLevel=impersonate}!Win32_PerfRawData_PerfOS_Processor.Name='_Total'");
        if (!$com)
            return false;

        $info[0] = $com->PercentProcessorTime;
        $info[1] = 0;
        $info[2] = 0;
        $info[3] = $com->TimeStamp_Sys100NS;

        return $info;
    }

    $statfile = '/proc/stat';
    if (!file_exists($statfile))
        return false;

    $fo = fopen($statfile, "r");
    if (!$fo)
        return false;

    $statinfo = explode("\n", fgets($fo, 1024));
    fclose($fo);
    foreach ($statinfo as $line)
    {
        $info = explode(" ", $line);
        if ($info[0] == "cpu")
        {
            array_shift($info);
            if (!$info[0])
                array_shift($info);
            return $info;
        }
    }
    return false;
}


function calc_CPU_Load()
{
    $info = _calc_CPU_Load();
    if (!$info)
        return false;

    if (empty($lastLoad))
    {
        sleep(1);
        $lastLoad = $info;
        $info = _calc_CPU_Load();
    }

    $last = $lastLoad;
    $lastLoad = $info;

    $_user = $info[0] - $last[0];
    $_nice = $info[1] - $last[1];
    $_system = $info[2] - $last[2];
    $_idle = $info[3] - $last[3];

    if (strncmp(PHP_OS, 'WIN', 3) == 0)
    {
        if ($_idle < 1)
            $_idle = 1;
        return 100 * (1 - $_user / $_idle);
    } else
    {
        $total = $_user + $_nice + $_system + $_idle;
        if ($total < 1)
            $total = 1;
        return 100 * ($_user + $_nice + $_system) / $total;
    }
}
?>

Usage:

<? echo calc_CPU_Load(); ?>

Online demo

In LINUX OS, we use file /proc/stat to calculate. This file keeps track of a variety of different statistics about the system since it was last restarted. The contents of /proc/stat, which can be quite long, usually begins like the following example:

cpu  606833 402 200307 3888129 69330 0 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0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
ctxt 91496615
btime 1334106197
processes 27829
procs_running 1
procs_blocked 0
softirq 8764373 0 5353481 964 133618 444766 0 560785 671622 2332 1596805

Some of the more commonly used statistics include:

  • cpu — Measures the number of jiffies (1/100 of a second for x86 systems) that the system has been in user mode, user mode with low priority (nice), system mode, idle task, I/O wait, IRQ (hardirq), and softirq respectively. The IRQ (hardirq) is the direct response to a hardware event. The IRQ takes minimal work for queuing the “heavy” work up for the softirq to execute. The softirq runs at a lower priority than the IRQ and therefore may be interrupted more frequently. The total for all CPUs is given at the top, while each individual CPU is listed below with its own statistics. The following example is a 4-way Intel Pentium Xeon configuration with multi-threading enabled, therefore showing four physical processors and four virtual processors totaling eight processors.
  • page — The number of memory pages the system has written in and out to disk.
  • swap — The number of swap pages the system has brought in and out.
  • intr — The number of interrupts the system has experienced.
  • btime — The boot time, measured in the number of seconds since January 1, 1970, otherwise known as the epoch.
  • ctxt – The total number of context switches across all CPUs.
  • processes – The number of processes and threads created, which includes (but is not limited to) those created by calls to the fork() and clone() system calls.
  • procs_running – The number of processes currently running on CPUs.
  • procs_blocked – The number of processes currently blocked, waiting for I/O to complete.

Leave a Reply