我正在进行一些算法分析,我决定测试三种文件读取方法,然后对它们进行基准测试(比较它们的平均执行时间)。首先,我生成一个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的文本文件,它似乎也很长。我的问题是:这些时间结果是否合理?如果没有,那些实现中是否有任何看起来不正确的东西?
答案 0 :(得分:1)
删除System.out.println(...)
可能会提高基准测试的效果,但请确保对读取String
执行某些操作,因此循环不会得到优化。