php how to calculate system processor/s load in percent

February 7, 2013

This simple function will allow us to control php performance at level we need.

/**
 * Calculates the processor load in %
 * @see sys_getloadavg
 * @author Ivan Gospodinow
 * @site ivangospodinow.com
 * @date 07.02.2013
 * @param int $coreCount
 * @param int $interval
 * @return float
 */
function systemLoadInPercent($coreCount = 2,$interval = 1){
	$rs = sys_getloadavg();
	$interval = $interval >= 1 && 3 <= $interval ? $interval : 1;
	$load  = $rs[$interval];
	return round(($load * 100) / $coreCount,2);
}

Example:

echo systemLoadInPercent();
//42

current system load : 18.03%

and more

function to get system cores

/**
 * @see http://icesquare.com/wordpress/phphow-to-get-the-number-of-cpu-cores-in-fedora-ubuntu-and-freebsd/
 */
function getSystemCores(){
	$cmd = "uname";
	$OS = strtolower(trim(shell_exec($cmd)));

	switch($OS){
	   case('linux'):
	      $cmd = "cat /proc/cpuinfo | grep processor | wc -l";
	      break;
	   case('freebsd'):
	      $cmd = "sysctl -a | grep 'hw.ncpu' | cut -d ':' -f2";
	      break;
	   default:
	      unset($cmd);
	}

	if ($cmd != ''){
	   $cpuCoreNo = intval(trim(shell_exec($cmd)));
	}
	return empty($cpuCoreNo) ? 1 : $cpuCoreNo;
}

tags: ,
posted in how to ?, php by Ivan Gospodinow

Follow comments via the RSS Feed | Leave a comment | Trackback URL

Leave Your Comment


Warning: Use of undefined constant XML - assumed 'XML' (this will throw an Error in a future version of PHP) in /home/c2kblate/sites/ivangospodinow.com/wp-content/plugins/wp-syntaxhighlighter/wp-syntaxhighlighter.php on line 1048
 
Powered by Wordpress and MySQL. Theme by Shlomi Noach, openark.org