输入文件是一个500万个32位整数对的长列表,由逗号分隔。像这样:
44439,5023 33140,22257 ...
这个文件在我的机器上占用5.5GB。程序不能使用超过8GB的RAM,只能使用单个线程。
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.50秒,计算时间为11.27秒。我正在与一个类似的C++基准测试竞争,该基准测试在大致相同的时间内进行IO,但计算仅需4.5秒。我的主要目标是以任何可能的方式减少计算时间。有什么想法吗?
更新:看起来主要的速度提升可能来自所谓的自动向量化。我能找到一些提示,表明当前Sun的JIT只做了“一些向量化”,但我无法确认。找到一些具有更好的自动向量化优化支持的JVM或JIT将是很好的。