我写了一个程序来测试try catch block 是否影响运行时间。 代码如下所示
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 和更大的数字时时间更少?它溢出了吗?似乎没有。
最佳答案
您没有测试 try/catch
block 的计算成本。您实际上是在测试异常处理 的成本。一个公平的测试是使 b= 2 ;
也在 ExceptionCase
中。如果你认为你只是在测试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
变量。
关于java - 为什么数字越大运行时间越少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18567960/