recover use of cpu with php

1

Well I put the following code in php, to return the CPU usage.

// 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% us, how do I get the code to return only this?

    
asked by anonymous 18.12.2018 / 20:02

1 answer

2

Use preg_match to get 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 string 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 variable $cpu_us[0] .

    
18.12.2018 / 20:37