java - 在Java中测试不同的文件读取方法

标签 java profiling benchmarking nio memory-mapped-files

我正在做一些算法分析,我决定测试三种文件读取方法,然后对它们进行基准测试(比较它们的平均执行时间)。首先,我生成一个 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/

相关文章:

代码基准测试统计 -

java - 如何在 web.xml 中引用 websphere Resource Environment Provider?

java - 将一个日历实例分配给另一个实例的问题

java - 使用Java命令设置属性文件的路径

Android:Eclipse 下有哪些分析工具可用于查看可伸缩性?

c++ - 您如何对内存消耗进行基准测试?

java - Liquibase 从 csv 加载数据

mysql - 像 mysql 一样的 apache bench

c# - 来自 Stack Overflow 的 MVC 迷你分析器(安装)

nginx - 围攻未知 react