我正在尝试使用 Java 5.0 x64(在 Windows XP 上)对一个大文件 (~4GB) 执行一次性读取。
一开始文件读取速度非常快,但逐渐吞吐量大幅下降,随着时间的推移,我的机器似乎 react 迟钝。
我使用 ProcessExplorer 监控文件 I/O 统计数据,看起来进程最初读取 500MB/秒,但这个速率逐渐下降到 20MB/秒左右。
关于保持文件 I/O 速率的最佳方法有什么想法,尤其是使用 Java 读取大文件时?
下面是一些显示“间隔时间”持续增加的测试代码。只需将至少 500MB 的文件传递给 Main。
import java.io.File;
import java.io.RandomAccessFile;
public class MultiFileReader {
public static void main(String[] args) throws Exception {
MultiFileReader mfr = new MultiFileReader();
mfr.go(new File(args[0]));
}
public void go(final File file) throws Exception {
RandomAccessFile raf = new RandomAccessFile(file, "r");
long fileLength = raf.length();
System.out.println("fileLen: " + fileLength);
raf.close();
long startTime = System.currentTimeMillis();
doChunk(0, file, 0, fileLength);
System.out.println((System.currentTimeMillis() - startTime) + " ms");
}
public void doChunk(int threadNum, File file, long start, long end) throws Exception {
System.out.println("Starting partition " + start + " to " + end);
RandomAccessFile raf = new RandomAccessFile(file, "r");
raf.seek(start);
long cur = start;
byte buf[] = new byte[1000];
int lastPercentPrinted = 0;
long intervalStartTime = System.currentTimeMillis();
while (true) {
int numRead = raf.read(buf);
if (numRead == -1) {
break;
}
cur += numRead;
if (cur >= end) {
break;
}
int percentDone = (int)(100.0 * (cur - start) / (end - start));
if (percentDone % 5 == 0) {
if (lastPercentPrinted != percentDone) {
lastPercentPrinted = percentDone;
System.out.println("Thread" + threadNum + " Percent done: " + percentDone + " Interval time: " + (System.currentTimeMillis() - intervalStartTime));
intervalStartTime = System.currentTimeMillis();
}
}
}
raf.close();
}
}
谢谢!
最佳答案
我非常怀疑您是否真的每秒从您的磁盘中获取 500MB。数据很可能由操作系统缓存 - 每秒 20MB 是数据真正到达磁盘时发生的情况。
这很可能在 Vista 资源管理器的磁盘部分可见 - 一种低技术含量的判断方法是听磁盘驱动器:)
关于Java 文件 I/O 性能随时间下降,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/342151/