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 : 309%

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

 
 
Powered by Wordpress and MySQL. Theme by Shlomi Noach, openark.org