第一行是当前系统CPU的数量,第一层级是package,第二层级是core,第三层级是thread。执行效果如下:
# php cputree.php cpus(16) +-0 | +-0 | | +-0 | | `-8 | +-1 | | +-1 | | `-9 | +-2 | | +-10 | | `-2 | `-3 | +-11 | `-3 `-1 +-0 | +-12 | `-4 +-1 | +-13 | `-5 +-2 | +-14 | `-6 `-3 +-15 `-7
|
php脚本代码如下所示:
#!/usr/bin/env php
<?php
$path = "/sys/devices/system/cpu";
chdir($path);
$cpus = glob("cpu*");
$packages = array();
foreach ($cpus as $cpu) {
chdir("$cpu/topology");
$package_id = intval(file_get_contents("physical_package_id"));
$core_id = intval(file_get_contents("core_id"));
$packages[$package_id][$core_id][] = intval(substr($cpu, 3));
chdir("../../");
}
echo "cpus(" . count($cpus) . ")\n";
$package_count = 0;
foreach ($packages as $package_id => $cores) {
$package_count++;
if ($package_count == count($packages)) {
echo " `-$package_id\n";
$package_prefix = " ";
} else {
echo " +-$package_id\n";
$package_prefix = " | ";
}
$core_count = 0;
foreach ($cores as $core_id => $threads) {
$core_count++;
if ($core_count == count($cores)) {
echo $package_prefix . "`-$core_id\n";
$core_prefix = $package_prefix . " ";
} else {
echo $package_prefix . "+-$core_id\n";
$core_prefix = $package_prefix . "| ";
}
$thread_count = 0;
foreach ($threads as $thread) {
$thread_count++;
if ($thread_count == count($threads))
echo $core_prefix . "`-$thread\n";
else
echo $core_prefix . "+-$thread\n";
}
}
}
?>
|
仔细观察,会发现上面的树打印脚本有很多相似代码,用迭代替换之:
#!/usr/bin/env php
<?php
$path = "/sys/devices/system/cpu";
chdir($path);
$cpus = glob("cpu*");
$packages = array();
foreach ($cpus as $cpu) {
chdir("$cpu/topology");
$package_id = intval(file_get_contents("physical_package_id"));
$core_id = intval(file_get_contents("core_id"));
$packages[$package_id][$core_id][] = intval(substr($cpu, 3));
chdir("../../");
}
echo "cpus(" . count($cpus) . ")\n";
function print_tree($prefix, $tree) {
$cnt = 0;
foreach ($tree as $branch_id => $branch) {
$cnt++;
if (!is_array($branch))
$branch_id = $branch;
if ($cnt == count($tree)) {
echo $prefix . "`-$branch_id\n";
$branch_prefix = $prefix . " ";
} else {
echo $prefix . "+-$branch_id\n";
$branch_prefix = $prefix . "| ";
}
if (is_array($branch))
print_tree($branch_prefix, $branch);
}
}
print_tree(" ", $packages);
?>
|