这是一个生成输入文件的示例,例如您描述的 10000 行长的输入文件,然后将其读回并执行您发布的计算并将结果打印到标准输出。为了获得最差的读取性能,我在读取文件时专门禁用了任何缓冲。正如其他人所建议的那样,我也根本没有做任何缓存。整个过程,包括生成文件、进行计算和打印结果,始终需要大约 520-550 毫秒。这几乎不是“慢”,除非您对数百或数千个文件重复相同的过程。如果您看到与此截然不同的性能,那么可能是硬件问题。出现故障的硬盘可能会使读取性能下降到几乎为零。
import java.io.*;
import java.util.Random;
public class ReadingDoublesFromFileEfficiency {
private static Random random = new Random();
public static void main(String[] args) throws IOException {
long start = System.currentTimeMillis();
String filePath = createInputFile();
BufferedReader reader = new BufferedReader(new FileReader(filePath), 1);
String line;
while ((line = reader.readLine()) != null) {
String[] details = line.split(",");
double score = (Double.parseDouble(details[0]) * Double.parseDouble(details[1])) + Double.parseDouble(details[2]) + Double.parseDouble(details[3]) + Double.parseDouble(details[6]);
System.out.println(score);
}
reader.close();
long elapsed = System.currentTimeMillis() - start;
System.out.println("Took " + elapsed + " ms");
}
private static String createInputFile() throws IOException {
File file = File.createTempFile("testbed", null);
PrintWriter writer = new PrintWriter(new FileWriter(file));
for (int i = 0; i < 10000; i++) {
writer.println(randomLine());
}
writer.close();
return file.getAbsolutePath();
}
private static String randomLine() {
return String.format("%f,%f,%f,%f,%s,%s,%f",
score(), score(), score(), score(), name(), name(), score());
}
private static String name() {
String name = "";
for (int i = 0; i < 10; i++) {
name += (char) (random.nextInt(26) + 97);
}
return name;
}
private static double score() {
return random.nextDouble() * 100;
}
}