recover cpu usage with php

Asked

Viewed 72 times

1

Well I built the following code in php, to return me the CPU use.

// Executa comando para consulta da CPU
exec('top -d 0 -n 5 -b | grep Cpu', $cpu);

// Monta array com os cores do processador
for($i=1; $i < count($cpu);$i++){
    $cores[] = $cpu[$i];
}

// Monta o array de resposta
$array = array(
"cpu" => array(
    "geral" => $cpu[0],
    "cores" => $cores
)
);

echo var_dump($array); 

The answer I have is:

"%Cpu(s):  8.5 us,  1.3 sy,  0.0 ni, 89.6 id,  0.1 wa,  0.0 hi,  0.5 si,  0.0 st"

Well I just wanted to see how to get the code back to me?

1 answer

2


Use the preg_match to pick up only 8.5 of 8.5 us:

preg_match('/\d+\../', $array['cpu']['geral'], $cpu_us);

echo $cpu_us[0]; // deve imprimir: "8.5"

The code will return the first sequence that meets the regular expression \d+\.., where:

\d+ : 1 ou mais números
\.  : seguido por um ponto
.   : mais outro caractere qualquer

Resulting in 8.5 in the variable $cpu_us[0].

Browser other questions tagged

You are not signed in. Login or sign up in order to post.