php-linux-cpu/lib/Cpu.php

133 lines
3.5 KiB
PHP

<?php
namespace NoccyLabs\Linux\Cpu;
class Cpu
{
/**
* @var string The path to the sys control files
*/
protected $sys_path = "/sys/devices/system/cpu";
/**
* @var int The number of CPUs in this system
*/
protected $num_cpus;
/**
* @var int[] The available scaling frequencies
*/
protected $available_frequencies;
/**
* @var string[] The available governors
*/
protected $available_governors;
/**
*
*/
public function __construct($path=null)
{
if ($path) {
$this->sys_path = $path;
}
$this->readSysInfo();
}
/**
* Read and cache information from sysfs
*
*/
protected function readSysInfo()
{
// Get number of CPU cores
$cpus = glob($this->sys_path . "/cpu?");
$this->num_cpus = count($cpus);
// Get the available CPU frequencies
$freq_raw = file_get_contents($this->sys_path."/cpu0/cpufreq/scaling_available_frequencies");
$freq_list = explode(" ", trim($freq_raw));
sort($freq_list);
$this->available_frequencies = array_map("intval", $freq_list);
// Get the available CPU governor
$govr_raw = file_get_contents($this->sys_path."/cpu0/cpufreq/scaling_available_governors");
$govr_list = explode(" ", trim($govr_raw));
sort($govr_list);
$this->available_governors = $govr_list;
}
/**
* Get the number of CPU cores in the system. The operations by the CPU
* class will operate on all cores.
*
* @return int The number of CPU cores
*/
public function getNumCpus()
{
return $this->num_cpus;
}
/**
* Get the available CPU frequencies in hertz for scaling.
*
* @return int[] The available CPU frequencies
*/
public function getAvailableFrequencies()
{
return $this->available_frequencies;
}
/**
* Get the current scaling frequency of the CPU in hertz.
*
* @return int The CPU frequency in Hz
*/
public function getCurrentFrequency()
{
$freq_curr = file_get_contents($this->sys_path."/cpu0/cpufreq/scaling_cur_freq");
return (int)$freq_curr;
}
public function setCurrentFrequency($freq)
{
if (!in_array((int)$freq, $this->available_frequencies)) {
$avail = join(", ", $this->available_frequencies);
throw new \InvalidArgumentException("CPU frequency {$freq} not supported (available: {$avail}");
}
file_put_contents($this->sys_path."/cpu0/cpufreq/scaling_cur_freq", (int)$freq);
}
/**
* Get a list of the available governors
*
* @return string[] The available governors
*/
public function getAvailableGovernors()
{
return $this->available_governors;
}
/**
* Get the currently active governor
*
* @return string The name of the currently active governor
*/
public function getCurrentGovernor()
{
$govr_curr = file_get_contents($this->sys_path."/cpu0/cpufreq/scaling_governor");
return trim($govr_curr);
}
public function setCurrentGovernor($governor)
{
if (!in_array((int)$governor, $this->available_governors)) {
$avail = join(", ", $this->available_governors);
throw new \InvalidArgumentException("Governor {$governor} not supported (available: {$avail}");
}
file_put_contents($this->sys_path."/cpu0/cpufreq/scaling_governor", $governor);
}
}