【问题标题】:why running time less when it number bigger为什么数字越大运行时间越少
【发布时间】:2013-09-02 07:41:01
【问题描述】:

我写了一个程序来测试try catch块是否影响运行时间。 代码如下所示

public class ExceptionTest {
    public static void main(String[] args) {
        System.out.println("Loop\t\tNormal(nano second)\t\tException(nano second)");
        int[] arr = new int[] { 1, 500, 2500, 12500, 62500, 312500, 16562500 };
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i] + "," + NormalCase(arr[i]) + ","
                    + ExceptionCase(arr[i]));
        }
    }

    public static long NormalCase(int times) {
        long firstTime=System.nanoTime();
        for (int i = 0; i < times; i++) {
            int a = i + 1;
            int b = 2;
            a = a / b;
        }
        return System.nanoTime()-firstTime;
    }

    public static long ExceptionCase(int times) {
        long firstTime =System.nanoTime();
        for (int i = 0; i < times; i++) {
            try {

                int a = i + 1;
                int b = 0;
                a = a / b;

            } catch (Exception ex) {
            }
        }
        return System.nanoTime()-firstTime;
    }
}

结果如下:

我想知道为什么变成 62500 和更大的数字的时间更少?它是否溢出?似乎没有。

【问题讨论】:

  • 相关:stackoverflow.com/q/504103/1065197,注意规则1到4。
  • 为了快速改进,请在您现在所做的所有事情周围添加一个外循环,它将整个测试重复至少 10 次。您还可以使用无限循环并在看到数字稳定时手动终止。

标签: java exception try-catch


【解决方案1】:

您没有测试try/catch 块的计算成本。您确实在测试异常处理的成本。一个公平的测试是在ExceptionCase 中创建b= 2 ;。如果您认为您只是在测试try/catch,我不知道您会得出什么极其错误的结论。坦率地说,我很震惊。

时间变化如此之大的原因是您执行函数的次数如此之多,以至于 JVM 决定编译和优化它们。将你的循环封装到一个外部循环中

    for(int e= 0 ; e < 17 ; e++ ) {
        for(int i= 0 ; i < arr.length ; i++) {
            System.out.println(arr[i] + "," + NormalCase(arr[i]) + "," + ExceptionCase(arr[i]));
        }
    }

您会在运行结束时看到更稳定的结果。

我还认为,在NormalCase 的情况下,优化器“意识到”for 并没有真正做任何事情,只是跳过它(执行时间为 0)。出于某种原因(可能是异常的副作用),它与ExceptionCase 不同。为了解决这个偏差,在循环中计算一些东西并返回它。

我不想过多更改你的代码,所以我将使用一个技巧来返回第二个值:

    public static long NormalCase(int times,int[] result) {
        long firstTime=System.nanoTime();
        int computation= 0 ;
        for(int i= 0; i < times; i++ ) {
            int a= i + 1 ;
            int b= 2 ;
            a= a / b ;
            computation+= a ;
        }
        result[0]= computation ;
        return System.nanoTime()-firstTime;
    }

您可以使用NormalCase(arr[i],result) 调用它,前面加上声明int[] result= new int[1] ;。以同样的方式修改ExceptionCase,并输出 result[0] 以避免任何其他优化。对于每个函数,您可能需要一个 result 变量。

【讨论】:

  • 非常感谢。我想知道如果发生异常需要多少时间。我描述得不好。抱歉。
  • @waylife 好的。我担心你没有意识到这一点并得出结论认为try/catch 是邪恶的或类似的东西:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-03
  • 1970-01-01
  • 1970-01-01
  • 2021-08-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多