问题
I am calling argon2 - memory intensive hashing function in Qt and measuring its running time:
...
QTime start = QTime::currentTime();
// call hashing function
QTime finish = QTime::currentTime();
time = start.msecsTo(finish) / 1000.0;
...
In argon2 library's test case, time is measured in another way:
...
clock_t start = clock();
// call hashing function
clock_t finish = clock();
time = ((double)finish - start) / CLOCKS_PER_SEC;
...
I am calling the function exactly as they call in their test case. But I am getting a twice bigger number (twice slower). Why? How to measure function running time in Qt? What clock() actually measures?
env:virtualBox, Ubuntu14.04 64bit, Qt5.2.1, Qt Creator 3.0.1.
回答1:
You could also try to use the 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
回答2:
clock() isn't accurate for measuring time spend in functions. It just returns number of ticks for whole program while its on CPU rightnow, it doesn't count blocking IO operations or sleeps. It just counts ticks which your program is running on CPU (processing). If you put sleep in your code you will loose CPU and this time isn't counting with clock(). You have to use time() or gettimeofday() or more accurate rdtsc assembly instruction.
Lookat these questions :
clock() accuracy
Why is CLOCKS_PER_SEC not the actual number of clocks per second?
In Qt sources, you will see the Qt has used gettimeofday for implementing QTime::currentTime() under Unix https://github.com/radekp/qt/blob/master/src/corelib/tools/qdatetime.cpp : line 1854
来源:https://stackoverflow.com/questions/41161491/how-to-measure-function-running-time-in-qt