【发布时间】:2012-03-24 05:54:10
【问题描述】:
查看下面的修改
终止检查没有进行强制转换。我认为
int:65 毫秒:
public void testWTF() throws Exception {
int runs = 10;
long hs = 0;
long timeSum = 0;
for (int run = 0; run < runs; run++) {
int term = Integer.MAX_VALUE;
long start = System.currentTimeMillis();
// ***** loop to be tested ******
for (int i = 0; i < term; i++) {
hs++;
}
timeSum += (System.currentTimeMillis() - start);
System.out.println("hs = " + hs);
hs = 0;
}
System.out.println("timeSum = " + timeSum);
System.out.println("avg time = " + (timeSum / runs) + " for " + runs + " runs");
System.out.println("hs = " + hs);
}
长:1445 毫秒
public void testWTF() throws Exception {
int runs = 10;
long hs = 0;
long timeSum = 0;
for (int run = 0; run < runs; run++) {
long term = Integer.MAX_VALUE;
long start = System.currentTimeMillis();
// ***** loop to be tested ******
for (long i = 0; i < term; i++) {
hs++;
}
timeSum += (System.currentTimeMillis() - start);
System.out.println("hs = " + hs);
hs = 0;
}
System.out.println("timeSum = " + timeSum);
System.out.println("avg time = " + (timeSum / runs) + " for " + runs + " runs");
System.out.println("hs = " + hs);
}
硬件:运行 windows 7 64bit 的 64 位 Xeon。
编辑:我对此进行了更新以进行多次迭代。使用 int 版本运行 100 万次,平均时间为 65 毫秒。对于 100 万次、1000 次甚至 100 次,长版本耗时太长。10 次运行的平均时间为 1447 毫秒。
另外,我在循环外使用 hs,这样循环就不会被忽略。
【问题讨论】:
-
你运行了多次吗?如果您只运行一次,就可以解释巨大的时差。
-
我无法确认您的结果。使用 int 版本 i 的平均时间为 1475 毫秒,长版本为 1463 毫秒,运行 10 次。在 JDK 7 更新 13 64 位的 Windows 8 64 位上运行