我想计算文件的MD5哈希值。
如果我使用fast_md5与本地库http://twmacinta.com/myjava/fast_md5.php,那么Java读取文件从硬盘90 MB/s…120MB/s,计算时间70秒。
如果使用QT
QCryptographicHash hash(QCryptographicHash::Md5);
QFile in("C:/file.mkv");
QFileInfo fileInfo("C:/file.mkv");
qint64 imageSize = fileInfo.size();
const int bufferSize = 1000000;
char buf[bufferSize+5];
int bytesRead;
if (in.open(QIODevice::ReadOnly)) {
while ( (bytesRead = in.read(buf, bufferSize)) > 0) {
// imageSize -= bytesRead;
// hash.addData(buf, bytesRead);
}
}
else {
qDebug() << "Failed to open device!";
}
in.close();
qDebug() << hash.result().toHex();
然后我的程序以20…78的速度从硬盘读取文件MB/s,计算时间为210秒。
是否有可能在QT中加速MD5 Calc的处理?可能需要将缓冲区从1000000增加到更大的值?
最佳解决方案是
/*max bytes to read at once*/
static const qint64 CHUNK_SIZE = 1024;
/*init hash*/
QCryptographicHash hash(Sha1);
/*open file*/
QFile file("foo.bar");
if (!file.open(QIODevice::ReadOnly))
return;
/*process file contents*/
QByteArray temp = file.read(CHUNK_SIZE);
while(!temp.isEmpty())
{
hash.addData(temp);
temp = file.read(CHUNK_SIZE);
}
/*finalize*/
const QByteArray res = hash.result();
qDebug("Hash is: %s", res.toHex());
这个解决方案为我提供了最好的读取速度(大约100- 120mb/s)和最好的计算时间- 51…75秒。
从https://qt-project.org/forums/viewthread/41886