如何检测安卓手机的CPU速度?

25

我想检测我的Android应用程序运行的设备速度有多快?

在Android上是否有任何API可以实现此功能?还是我必须自己进行基准测试?

如果设备的CPU速度较慢,我希望关闭一些耗时操作,如动画或限制同时进行的最大HTTP请求次数。

4个回答

25

在我看来,最好的方法是监控执行这些操作所需的时间。如果花费的时间过长,则系统太慢了,您可以在它变快之前禁用高级功能。

读取CPU速度或其他规格并试图判断系统速度是一个坏主意。未来硬件的更改可能会使这些规格毫无意义。

以 Pentium 4 和 Core 2 为例。哪个 CPU 更快,2.4 GHz 的 Pentium 4 还是 1.8 GHz 的 Core 2?2 GHz 的 Opteron 是否比 1.4 GHz 的 Itanium 2 更快?你怎么知道哪种 ARM CPU 实际上更快?

为了获取 Windows Vista 和 7 的系统速度评级,微软实际上对机器进行基准测试。这是唯一半准确的确定系统功能的方法。

看起来一个好的方法是使用SystemClock.uptimeMillis()。


我应该只使用System.currentTimeMillis()来计算时间吗? - Dariusz Bacinski
@darbat:http://developer.android.com/reference/android/os/SystemClock.html 尝试使用uptimeMillis()。 - Zan Lynx
@ZanLynx:我正在尝试解决同样的问题,但在我的经验中,由于后台进程,Android上的CPU基准测试非常不准确。你找到了缓解这个问题的方法吗? - Simplex
@JonnyBoy:尽力而为。如果你能够通过定时重要操作来随时适应,那就是最好的方法。许多 GUI 动画在系统过于繁忙时会跳过中间帧来实现这一点。 - Zan Lynx

8

尝试阅读/proc/cpuinfo,其中包含CPU信息:

   String[] args = {"/system/bin/cat", "/proc/cpuinfo"};
   ProcessBuilder pb = new ProcessBuilder(args);

   Process process = pb.start();
   InputStream in = process.getInputStream();
   //read the stream

2
这是一个相当糟糕的想法。我的意思是,它会工作。但是,如果在未来某个版本的CPU上运行时执行更多工作但速度较慢,你的应用程序将会怎样呢?如果应用程序在Pentium 4上执行此操作,那么当Core2推出时,该应用程序将显得很愚蠢。 - Zan Lynx
2
抱歉,我应该更多地向darbat发表评论。 - Zan Lynx

2

基于@dogbane的解决方案和这个答案,这是我获取BogoMIPS值的实现:

 /**
 * parse the CPU info to get the BogoMIPS.
 * 
 * @return the BogoMIPS value as a String
 */
public static String getBogoMipsFromCpuInfo(){
    String result = null;
    String cpuInfo = readCPUinfo();
    String[] cpuInfoArray =cpuInfo.split(":");
    for( int i = 0 ; i< cpuInfoArray.length;i++){
        if(cpuInfoArray[i].contains("BogoMIPS")){
            result = cpuInfoArray[i+1];
            break;
        }
    }
    if(result != null) result = result.trim();
    return result;
}

/**
 * @see {https://dev59.com/KnA75IYBdhLWcg3w899J#3021088}
 *
 * @return the CPU info.
 */
public static String readCPUinfo()
{
    ProcessBuilder cmd;
    String result="";
    InputStream in = null;
    try{
        String[] args = {"/system/bin/cat", "/proc/cpuinfo"};
        cmd = new ProcessBuilder(args);
        Process process = cmd.start();
        in = process.getInputStream();
        byte[] re = new byte[1024];
        while(in.read(re) != -1){
            System.out.println(new String(re));
            result = result + new String(re);
        }
    } catch(IOException ex){
        ex.printStackTrace();
    } finally {
            try {
                if(in !=null)
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
    return result;
}

3
为了获得一个有效的bogoMIPS读数,我不得不更改上面代码中的分割正则表达式:String[] cpuInfoArray =cpuInfo.split(":|\\n");谢谢。 - Andrew Aarestad

0

仅提供链接的回答。 - Stephen C

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接