Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 如何取得手機 CPU 核心數並判斷單核或多核

編輯:關於 Android 程式設計

想知道手上的 Android 裝置是單核還是多核?系統並沒有提供現成的 API,但方法是有的:去數 /sys/devices/system/cpu/ 目錄底下有幾個 cpuN 資料夾。有幾個,就是幾核。

實現代碼

/**
 * Gets the number of cores available in this device, across all processors.
 * Requires: Ability to peruse the filesystem at "/sys/devices/system/cpu"
 * @return The number of cores, or 1 if failed to get result
 */
private int getNumCores() {
    // Private Class to display only CPU devices in the directory listing
    class CpuFilter implements FileFilter {
        @Override
        public boolean accept(File pathname) {
            // Check if filename is "cpu", followed by a single digit number
            if (Pattern.matches("cpu[0-9]", pathname.getName())) {
                return true;
            }
            return false;
        }
    }

    try {
        // Get directory containing CPU info
        File dir = new File("/sys/devices/system/cpu/");
        // Filter to only list the devices we care about
        File[] files = dir.listFiles(new CpuFilter());
        // Return the number of cores (virtual CPU devices)
        return files.length;
    } catch (Exception e) {
        // Default to return 1 core
        return 1;
    }
}

程式碼在說什麼

整個做法分三個環節:

  1. 用一個內部的 CpuFilter 實作 FileFilter,只放行檔名符合 cpu0、cpu1、cpu2… 這種格式的項目。這麼做是為了排除同目錄下的 cpufreq、cpuidle 等雜項檔案或目錄。
  2. 用 dir.listFiles(filter) 取得篩選後的陣列。
  3. 回傳 files.length,也就是核心數。任何例外都回退為 1。

要判斷單核還是多核,只要拿回傳值比較即可:

int cores = getNumCores();
if (cores > 1) {
    // 多核
} else {
    // 單核
}

幾個實務上的限制

正規表達式的位數問題。cpu[0-9] 只能匹配個位數。理論上手機不會有 10 顆以上的核心,但若要寫得更嚴謹,可改成 cpu[0-9]+。

權限與相容性。這個方法依賴能讀取 /sys 這個 sysfs 路徑。多數情況下不需要特殊權限即可讀取,但部分客製化 ROM 或較新的 Android 版本可能限制存取,這也正是程式碼裡必須用 try-catch 保底的原因。

「實體核心」不等於「同時可用核心」。行動裝置普遍採用 big.LITTLE 架構,平時為了省電會把部分核心關閉(hotplug)。getNumCores() 回傳的是硬體上的核心總數,而非當下實際有幾顆在跑。若你的用途是效能調校、決定執行緒數量,建議改用 Runtime.getRuntime().availableProcessors(),它反映的是目前可用的處理器數量,判斷起來更貼近真實情況。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved