0

我想计算文件的 MD5 哈希。

如果我将 fast_md5 与本机库http://twmacinta.com/myjava/fast_md5.php一起使用,则 Java 从 HDD 读取文件的速度为 90 MB/s...120 MB/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 的速度从 HDD 读取文件,计算时间为 210 秒。

是否可以在 QT 中加速 MD5 Calc 的处理?可能需要将缓冲区从 1000000 增加到更大的值?

4

1 回答 1

0

最好的解决方案是

/*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-120 MB/s)和最佳计算时间 - 51...75 秒。

来自https://qt-project.org/forums/viewthread/41886

于 2014-07-29T14:23:06.867 回答