如何在 Qt 中测量函数 运行 时间?

How to measure function running time in Qt?

我正在调用 argon2 - Qt 中的内存密集型哈希函数并测量其 运行 时间:

...
QTime start = QTime::currentTime();
// call hashing function
QTime finish = QTime::currentTime();
time = start.msecsTo(finish) / 1000.0;
...

在argon2库的测试用例中,时间是用另一种方式测量的:

...
clock_t start = clock();
// call hashing function
clock_t finish = clock();
time = ((double)finish - start) / CLOCKS_PER_SEC;
...

我调用的函数与他们在测试用例中调用的完全一样。但我得到的数字要大两倍(慢两倍)。为什么?如何在 Qt 中测量函数 运行 时间? clock() 实际测量的是什么?

env:virtualBox, Ubuntu14.04 64bit, Qt5.2.1, Qt Creator 3.0.1.

clock() 无法准确测量函数花费的时间。它只是 returns 整个程序的滴答数,而它现在处于 CPU 状态,它不计算阻塞 IO 操作或睡眠。它只计算您的程序在 CPU(处理)上 运行 的滴答声。如果你在你的代码中加入 sleep ,你将失去 CPU 并且这个时间不计入 clock()。 您必须使用 time() 或 gettimeofday() 或更准确的 rdtsc 汇编指令。

看看这些问题:

clock() accuracy

Why is CLOCKS_PER_SEC not the actual number of clocks per second?

在 Qt 源代码中,您会看到 Qt 在 Unix 下使用 gettimeofday 来实现 QTime::currentTime() https://github.com/radekp/qt/blob/master/src/corelib/tools/qdatetime.cpp:第 1854 行

您也可以尝试使用 QElapsedTimer:

QElapsedTimer timer;
timer.start();

slowOperation1();

qDebug() << "The slow operation took" << timer.elapsed() << "milliseconds";
qDebug() << "The slow operation took" << timer.nsecsElapsed() << "nanoseconds";

Documentation of QElapsed Timer