我的手机有一个ARM big.LITTLE cpu,我正在制作一个将永远运行的程序
while(1) {
do_stuff();
sleep_seconds(60);
}
而且do_stuff()函数可能使用了太多的cpu,以至于每次运行时都会唤醒性能核心。如果可能的话,我想避免那样做。我可以从理论上说给它尽可能低的cpu优先级,
setpriority(PRIO_PROCESS, 0, 19);
可能会起作用,但这只是一个疯狂的猜测,我不知道这是否真的有效。帮助?
发布于 2022-04-11 15:09:56
我想我想出来了!假设高效的核心是最高频率最低的核心(我认为总是这样?),我们可以使用
/sys/devices/system/cpu/cpu*/cpufreq/cpuinfo_max_freq
猫
为了推导出哪些核心是性能核心,哪些核心是功耗高的核心,那么我们可以使用tasket
来限制我们自己的核心。例如,在我的Mediatek Helio G95 (Ulefone Armor 13)上:
u0_a210@localhost:~$ cat /sys/devices/system/cpu/cpu*/cpufreq/cpuinfo_max_freq
2000000
2000000
2000000
2000000
2000000
2000000
2050000
2050000
最后两个核心是性能核心。因此我们可以用
taskset --pid --all-tasks 0,1,2,3,4,5 PID
将PID限制在只有高效电源的核心上。PHP中的示例实现:
function restrict_to_slowest_cores(bool $print_debug_info = false): void {
// cat /sys/devices/system/cpu/cpu*/cpufreq/cpuinfo_max_freq
$slowest_cores = [ ];
$slowest_freq = INF;
$path = "";
for($i = 0;; ++ $i) {
$path = "/sys/devices/system/cpu/cpu{$i}/cpufreq/cpuinfo_max_freq";
if (! file_exists ( $path )) {
// found the last core i hope..
break;
}
$freq = ( float ) file_get_contents ( $path );
if ($freq < $slowest_freq) {
// slower than any previously checked core! trash the entire previous list.
// (the previous list is either empty or contain exclusively faster cores)
$slowest_cores = [
$i
];
$slowest_freq = $freq;
} elseif ($freq === $slowest_freq) {
// this is among the slowest cores we've seen thus far, add it to the list.
$slowest_cores [] = $i;
} else {
// this is one of the faster cores, ignore it.
}
}
if ($i === 0) {
throw new \RuntimeException ( "unable to find any cpu freq! file missing/unreadable: {$path}" );
}
$cmd = "taskset --pid --all-tasks " . implode ( ",", $slowest_cores ) . " " . getmypid ();
if (! $print_debug_info) {
$cmd .= " >/dev/null";
}
if ($print_debug_info) {
var_dump ( [
"slowest cores" => $slowest_cores,
"last path" => $path,
"cmd" => $cmd
] );
}
$ret = null;
passthru ( $cmd, $ret );
if ($ret !== 0) {
throw new RuntimeException ( "taskset failed! should return 0 but returned: {$ret} - cmd: {$cmd}" );
}
}
restrict_to_slowest_cores (true);
指纹:
u0_a210@localhost:~$ php test.php
array(3) {
["slowest cores"]=>
array(6) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(2)
[3]=>
int(3)
[4]=>
int(4)
[5]=>
int(5)
}
["last path"]=>
string(53) "/sys/devices/system/cpu/cpu8/cpufreq/cpuinfo_max_freq"
["cmd"]=>
string(43) "taskset --pid --all-tasks 0,1,2,3,4,5 30402"
}
pid 30402's current affinity mask: ff
pid 30402's new affinity mask: 45
成功!
https://stackoverflow.com/questions/71731060
复制相似问题