我正在尝试测试 Java 执行一项简单任务的速度有多快:将一个大文件读入内存,然后对数据执行一些无意义的计算。所有类型的优化都很重要。无论是以不同的方式重写代码还是使用不同的 JVM,欺骗 JIT ..
输入文件是一个由逗号分隔的 5 亿长的 32 位整数对列表。像这样:
44439,5023
33140,22257
...
该文件需要5.5GB在我的机器上。该程序不能使用超过8GBRAM 且只能使用单线程.
package speedracer;
import java.io.FileInputStream;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class Main
{
public static void main(String[] args)
{
int[] list = new int[1000000000];
long start1 = System.nanoTime();
parse(list);
long end1 = System.nanoTime();
System.out.println("Parsing took: " + (end1 - start1) / 1000000000.0);
int rs = 0;
long start2 = System.nanoTime();
for (int k = 0; k < list.length; k++) {
rs = calc(list[k++], list[k++], list[k++], list[k]);
}
long end2 = System.nanoTime();
System.out.println(rs);
System.out.println("Calculations took: " + (end2 - start2) / 1000000000.0);
}
public static int calc(final int a1, final int a2, final int b1, final int b2)
{
int c1 = (a1 + a2) ^ a2;
int c2 = (b1 - b2) << 4;
for (int z = 0; z < 100; z++) {
c1 ^= z + c2;
}
return c1;
}
public static void parse(int[] list)
{
FileChannel fc = null;
int i = 0;
MappedByteBuffer byteBuffer;
try {
fc = new FileInputStream("in.txt").getChannel();
long size = fc.size();
long allocated = 0;
long allocate = 0;
while (size > allocated) {
if ((size - allocated) > Integer.MAX_VALUE) {
allocate = Integer.MAX_VALUE;
} else {
allocate = size - allocated;
}
byteBuffer = fc.map(FileChannel.MapMode.READ_ONLY, allocated, allocate);
byteBuffer.clear();
allocated += allocate;
int number = 0;
while (byteBuffer.hasRemaining()) {
char val = (char) byteBuffer.get();
if (val == '\n' || val == ',') {
list[i] = number;
number = 0;
i++;
} else {
number = number * 10 + (val - '0');
}
}
}
fc.close();
} catch (Exception e) {
System.err.println("Parsing error: " + e);
}
}
}
我已经尝试了所有我能想到的。尝试不同的阅读器,尝试过openjdk6、sunjdk6、sunjdk7。尝试过不同的读者。由于 MappedByteBuffer 无法一次映射超过 2GB 的内存,因此必须进行一些丑陋的解析。我在跑:
Linux AS292 2.6.38-11-generic #48-Ubuntu SMP
Fri Jul 29 19:02:55 UTC 2011
x86_64 GNU/Linux. Ubuntu 11.04.
CPU: is Intel(R) Core(TM) i5-2410M CPU @ 2.30GHz.
目前,我的结果是解析:26.50s,计算:11.27s。我正在与一个类似的 C++ 基准测试进行竞争,该基准测试执行 IO 的时间大致相同,但计算只需要 4.5 秒。我的主要目标是尽一切可能减少计算时间。有任何想法吗?
Update:看来主要的速度改进可能来自所谓的自动矢量化 http://cplusplus-soup.com/2009/02/12/auto-vectorization-and-c/。我能够找到一些提示,表明当前 Sun 的 JIT 只进行“一些矢量化”,但我无法真正确认这一点。如果能找到一些具有更好自动向量化优化支持的 JVM 或 JIT,那就太好了。