我正在做一些算法分析,我决定测试三种文件读取方法,然后对它们进行基准测试(比较它们的平均执行时间)。首先,我生成一个 larde 文本文件(几百 MB),然后对每种方法运行十次测试 - 缓冲读取器、正常 IO 读取和内存映射读取:
public static void bufferedRead(String filename) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(filename));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void NIORead(String filename) throws IOException {
RandomAccessFile aFile = new RandomAccessFile(filename, "r");
FileChannel inChannel = aFile.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (inChannel.read(buffer) > 0) {
buffer.flip();
for (int i = 0; i < buffer.limit(); i++) {
System.out.print((char) buffer.get());
}
buffer.clear();
}
inChannel.close();
aFile.close();
}
public static void memoryMapRead(String filename) throws IOException {
RandomAccessFile aFile = new RandomAccessFile(filename, "r");
FileChannel inChannel = aFile.getChannel();
MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY,
0, inChannel.size());
buffer.load();
for (int i = 0; i < buffer.limit(); i++) {
System.out.print((char) buffer.get());
}
buffer.clear();
inChannel.close();
aFile.close();
}
但是,整个过程(3x10 测量)需要很长时间,比如 9 个小时左右。确实,我没有 SSD 磁盘,但即使对于 400 MB 的文本文件来说,它对我来说仍然很长。我的问题是:这些时间结果可信吗?如果不是,这些实现中是否有任何看起来不正确的地方?
最佳答案
删除System.out.println(...)
可能会提高基准测试的性能,但请确保对读取的String
执行一些操作,以便循环不要被优化掉。
关于java - 在Java中测试不同的文件读取方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29594168/