1. 观察CPU文件节点的特征
- 手机的CPU节点的路径:
device:/sys/devices/system/cpu $ ls -al
total 0
drwxr-xr-x 19 root root 0 2022-01-30 13:52 .
drwxr-xr-x 7 root root 0 2022-01-30 13:52 ..
drwxr-xr-x 10 root root 0 2022-01-30 13:52 cpu0
drwxr-xr-x 8 root root 0 2022-02-06 09:36 cpu1
drwxr-xr-x 8 root root 0 2022-02-06 09:36 cpu2
drwxr-xr-x 8 root root 0 2022-02-06 09:36 cpu3
drwxr-xr-x 8 root root 0 2022-02-06 09:36 cpu4
drwxr-xr-x 8 root root 0 2022-02-06 09:36 cpu5
drwxr-xr-x 9 root root 0 2022-02-06 09:36 cpu6
drwxr-xr-x 8 root root 0 2022-02-06 09:36 cpu7
- 路径特征
即都是/sys/devices/system/cpu/下不同名称。cpu0~cpu7分别表示不同的CPU核
/sys/devices/system/cpu/cpu0
/sys/devices/system/cpu/cpu1
/sys/devices/system/cpu/cpu2
/sys/devices/system/cpu/cpu3
/sys/devices/system/cpu/cpu4
/sys/devices/system/cpu/cpu5
/sys/devices/system/cpu/cpu6
/sys/devices/system/cpu/cpu7
- 文件名称特征
如何用字符串表示:cpu0~cpu7的名称特征:可以使用正则式:^cpu\d+
解释如下:
^cpu表示:字符串开头要为cpu
\d+:表示:数字为1个或或1个以上
^cpu\d+表示:字符串开头为cpu,cpu后的字符串要为数字,数字需要存在1个或1个以上
2. 编码
先访问CPU固定路径/sys/devices/system/cpu/,然后统计该路径过滤出符合cpu0~cpu7的名称特征的数量
2.1 demo
package com.sufadi.study
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import java.io.File
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d("shz_debug", "getCpuCoreSize: ${getCpuCoreSize()}")
}
private fun getCpuCoreSize() :Int {
var cpuDir = File("/sys/devices/system/cpu/")
val regex = Regex("^cpu\\d+$")
return cpuDir.listFiles().filter { file ->
null != regex.find(file.name)
}.size
}
}
2.2 运行结果
2022-02-06 10:34:02.444 29651-29651/com.sufadi.study D/shz_debug: getCpuCoreSize: 8