Skip to content

Instantly share code, notes, and snippets.

@brisbanewebdeveloper
Last active August 29, 2015 14:24
Show Gist options
  • Save brisbanewebdeveloper/04d547937e111e6d0aa3 to your computer and use it in GitHub Desktop.
Save brisbanewebdeveloper/04d547937e111e6d0aa3 to your computer and use it in GitHub Desktop.
Get percentage of time that the CPU was idle from sar command as JavaScript variable
<?php
/**
* Place this PHP script somewhere accessible via HTTP, amend it for your situation if necessary
*
* Example Usage with jQuery
* $.getScript(
* 'http://my-site.com/get-sar.php',
* function() {
* // You can use something like http://www.chartjs.org/ to display the data as chart
* console.log(sarData.data[0].time);
* console.log(sarData.data[0].idle);
* console.log(sarData.avg.idle);
* }
* );
*/
$sar = '/usr/bin/sar -u'; // You may have to amend here
exec($sar, $sarResults);
// var_dump($sarResults); exit;
$data = array();
foreach ($sarResults as $r) {
if (strpos($r, 'Linux') !== false) continue;
if ($r == '') continue;
sscanf($r, "%s%s%s%s%s%s%s%s\n", $time, $cpu, $user, $nice, $system, $iowait, $steal, $idle);
if ($cpu == 'CPU') continue;
if ($time == 'Average:') {
$data['avg'] = $idle;
continue;
}
// echo $time . $cpu . $user . $nice . $system . $iowait . $steal . $idle . "\n";
$data['data'][] = array(
'time' => $time,
'idle' => $idle,
);
}
header('Content-Type:text/javascript; charset=utf-8');
echo 'var sarData = ' . json_encode($data) . ';';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment