优化:在根文件夹下递归计算大量文件的MD5哈希



My当前生成根目录下所有文件的MD5哈希的方法如下所示。

截至目前,处理appx 300个图像大约需要10秒(旧的英特尔酷睿i3 cpu(,每个图像的大小平均为5-10 MB。stream中的parallel选项没有帮助。无论有没有它,时间都或多或少保持不变。我怎样才能更快?

Files.walk(Path.of(rootDir), depth)
.parallel() // doesn't help, time appx same as without parallel
.filter(path -> !Files.isDirectory(path)) // skip directories
.map(FileHash::getHash)
.collect(Collectors.toList());

上面使用的getHash方法为流中正在处理的每个文件提供了一个逗号分隔的hash,<full file path>输出行。

public static String getHash(Path path) {
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
md5.update(Files.readAllBytes(path));
} catch (Exception e) {
e.printStackTrace();
}
byte[] digest = md5.digest();
String hash = DatatypeConverter.printHexBinary(digest).toUpperCase();
return String.format("%s,%s", hash, path.toAbsolutePath());
}

Files.walk(Path.of(rootDir), depth)返回的流无法有效地并行化(他没有大小,因此很难确定要并行化的切片(。为了提高性能,您需要首先收集Files.walk(...)的结果。

所以你必须做:

Files.walk(Path.of(rootDir), depth)
.filter(path -> !Files.isDirectory(path)) // skip directories
.collect(Collectors.toList())
.stream()
.parallel() // in my computer divide the time needed by 5 (8 core cpu and SSD disk)
.map(FileHash::getHash)
.collect(Collectors.toList());

最新更新