【发布时间】:2012-01-31 17:05:18
【问题描述】:
我正在测试 Java 中整数加法的性能。我这样做的方法是对数十亿个整数求和。我用于测试的示例文件是一个 1G 的二进制文件。我的程序很简单,如下面的sn-p所示。
int result = 0;
FileChannel fileChannel = new FileInputStream(filename).getChannel();
long fileSize = fileChannel.size();
intBuffer = fileChannel.map(MapMode.READ_ONLY, startPosition, fileSize).asIntBuffer();
try {
while (true) {
result += intBuffer.get();
}
} catch (BufferUnderflowException e) {
System.out.println("Complete reading");
}
从上面可以看出,它只是在每个循环中执行两个操作
- 从文件中读取整数
- 整数加法
这个程序在我的机器上运行了大约 2 分钟。我还进行了另一次不添加的测试,将result += intBuffer.get() 更改为result = intBuffer.get()(如下面的sn-p 所示)。
int result = 0;
FileChannel fileChannel = new FileInputStream(filename).getChannel();
long fileSize = fileChannel.size();
intBuffer = fileChannel.map(MapMode.READ_ONLY, startPosition, fileSize).asIntBuffer();
try {
while (true) {
result = intBuffer.get();
}
} catch (BufferUnderflowException e) {
System.out.println("Complete reading");
}
在这种情况下,整个程序在 1 秒内完成。与上面的同级变体相比,与 IO 读取相比,整数加法似乎在 CPU 时间中占主导地位。
为了证明我的猜测,我编写了另一个基准程序,它执行的加法次数与上面的示例相同。
int result = random.nextInt();
int other = random.nextInt();
int num = 1073741824 / 4;
while(num-- > 0) {
result += other;
}
在相同数量的整数加法加上整数增量操作的情况下,这个程序不到 1 秒就完成了。
我的问题是
- 是什么导致了这些运行之间的主要时间差异? Java 编译器是否会优化最后一个?
感谢任何想法。
【问题讨论】:
-
您可能想澄清“第二个”的含义。我认为它是指您在
result = intBuffer.get()进行的测试,但2 个答案(到目前为止)似乎假设您的意思是您使用random.nextInt()的那个。 -
发生这种情况是因为操作系统将最近使用的文件保存在内存中。尝试以相反的顺序再运行一次测试。
-
@Baqueta,我调整了措辞以使问题更清楚。
标签: java performance integer addition