【问题标题】:In Android, how to measure the execution time overhead programmatically?在 Android 中,如何以编程方式测量执行时间开销?
【发布时间】:2016-01-18 20:30:31
【问题描述】:

虽然可能有类似的问题(如A),但他们的回答并不能解决我的问题。

我正在使用面向 Android API 18 的 Android Studio 1.5.1(在 Android KitKat 4.4 之前,所以我处理的是 Dalvik,而不是 ART 运行时)。

我有一个修改过的 Android,它增加了内存空间开销(由作者专门设计,超出了这个问题的范围)与任何使用的变量。例如,如果我们声明一个整数变量,该变量将存储在 8 个字节(64 位)而不是 4 个字节(32 位)中。此修改对于可以在修改后的 Android 上运行而没有任何问题的应用程序是完全透明的。

我需要测量执行时间的开销,例如,当我使用变量时。

这是我到目前为止所做的,但它似乎不起作用,因为开销变量(在下面代码中 //Method #1 的末尾)不一致,有时它是负数、正数或零。在理想的解决方案中,它应该始终(或至少大部分时间)为正。

      long start, end, time1, time2, overhead;

    //Baseline
    start = System.nanoTime();
    total=0; total+=1; total+=2; total+=3; total+=4; total+=5; total+=6;
    total+=7; total+=8; total+=9;
    end = System.nanoTime();
    System.out.println("********************* The sum is " + total);
    time1 =  end - start;
    System.out.println("********************* start=" + start + " end=" + end + " time=" + time1);

    //Method #1
    start = System.nanoTime();
    total = (a0() + a1() + a2() + a3() + a4() + a5() + a6() + a7() + a8() + a9());
    end = System.nanoTime();
    System.out.println("********************* The sum is " + total);
    time2 =  end - start;
    System.out.println("********************* start=" + start + " end=" + end + " time=" + time2);

    overhead = time2 - time1;
    System.out.println("********************* overhead=" + overhead );    
}
private int a0()
{
    return 0;
}
private int a1()
{
    return 1;
}
private int a2()
{
    return 2;
}
private int a3()
{
    return 3;
}
private int a4()
{
    return 4;
}
private int a5()
{
    return 5;
}
private int a6()
{
    return 6;
}
private int a7()
{
    return 7;
}
private int a8()
{
    return 8;
}
private int a9()
{
    return 9;
}

我的问题是:

在 Android 中,如何以编程方式测量执行时间开销?

【问题讨论】:

    标签: java android performance compiler-optimization dalvik


    【解决方案1】:

    您所描述的只是实验错误。

    开销变量不一致,有时为负数, 正数或零。在理想的解决方案中,它应该总是(或在 至少大部分时间)是积极的。

    我没有针对您在 Android 上的问题的确切解决方案,但是当我在其他环境中进行实验测试时,我通常会运行多次迭代,然后除以迭代次数以获得平均值。

    这是一些伪代码:

    int N = 10000;
    
    startTimer();
    for (int i = 0; i < N; i++) {
      runExperiment();
    }
    stopTimer();
    
    double averageRuntime = timer / N;
    

    【讨论】:

      【解决方案2】:

      问题是您尝试计时的代码执行速度比System.nanotime() 的分辨率快。尝试循环添加,例如

      for (int i = 0; i < 1000; i++) {
          total += i;
      }
      

      增加循环计数 (1000),直到您开始获得合理的经过时间。

      【讨论】:

        猜你喜欢
        • 2013-09-28
        • 1970-01-01
        • 2022-06-30
        • 2020-07-14
        • 2013-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多