我正在做多线程双核优化,它的工作原理是这样的:如果设备有双核处理器,则创建两个线程来进行计算,如果设备只有单核处理器,则只创建一个线程来进行计算。
我的问题是:我的程序如何知道一个设备是否是双核的?我只想有一个程序可以在双核和单核设备上运行,所以它必须能够知道这些信息。
代码如下:
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核)和华硕Transformer Prime(4核)上测试了这种方法,报告正确。下面是一些示例代码(取自我对这个问题的回答):
/**
* 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;
}
}
是否Runtime.availableProcessors()在2核设备上无法正确报告?