我正在通过多线程进行双核优化,它的工作原理如下:
如果设备具有双核处理器,则创建两个线程进行计算,如果设备只有一核处理器,则仅创建一个线程进行计算。
我的问题是:我的程序如何知道设备是否是双核?
我只想有一个程序可以在双核和单核设备上运行,所以它必须能够知道这些信息。
像这样的代码:
if( xxx_API_is_device_dual_core() ) // Inside if() is the expected API
{
saveThread = new SaveThread[2];
}
else
{
saveThread = new SaveThread[1];
}
非常感谢您的帮助!
Runtime.availableProcessors() 似乎并不适用于所有 Android 设备(例如,它在我的双核 Galaxy S II 上仅返回“1”)。物理 CPU 和虚拟 CPU(又名核心)之间可能存在一些混淆。
我发现的最可靠的方法是。基本上,您必须计算 /sys/devices/system/cpu/ 中的虚拟 CPU 设备。这将适用于双核和四核设备,无需修改。
我已在我的 Galaxy S II(2 核)和 Asus Transformer Prime(4 核)上测试了此方法,并且报告正确。这是一些示例代码(摘自我对这个问题的回答 https://stackoverflow.com/a/10377934/663469):
/**
* 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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)