C++ 在 Qt 中获取经过的时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/244646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get elapsed time in Qt
提问by shoosh
I'm looking for the equivalent in Qt to GetTickCount()
我正在寻找 Qt 中的等价物 GetTickCount()
Something that will allow me to measure the time it takes for a segment of code to run as in:
可以让我测量一段代码运行所需的时间,如下所示:
uint start = GetTickCount();
// do something..
uint timeItTook = GetTickCount() - start;
any suggestions?
有什么建议?
回答by sivabudh
I think it's probably better to use QElapsedTimer
since that is why the class exists in the first place. It was introduced with Qt 4.7. Note that it is also immuned to system's clock time change.
我认为使用它可能更好,QElapsedTimer
因为这就是该类首先存在的原因。它是在 Qt 4.7 中引入的。请注意,它也不受系统时钟时间变化的影响。
Example usage:
用法示例:
#include <QDebug>
#include <QElapsedTimer>
...
...
QElapsedTimer timer;
timer.start();
slowOperation(); // we want to measure the time of this slowOperation()
qDebug() << timer.elapsed();
回答by Dusty Campbell
回答by Lilian A. Moraru
Even if the first answer was accepted, the rest of the people who read the answers should consider sivabudh
's suggestion. QElapsedTimer
can also be used to calculate the time in nanoseconds.
Code example:
即使第一个答案被接受,其余阅读答案的人也应该考虑sivabudh
的建议。QElapsedTimer
也可用于计算以纳秒为单位的时间。
代码示例:
QElapsedTimer timer;
qint64 nanoSec;
timer.start();
//something happens here
nanoSec = timer.nsecsElapsed();
//printing the result(nanoSec)
//something else happening here
timer.restart();
//some other operation
nanoSec = timer.nsecsElapsed();
回答by Oliver Hoffmann
If you want to use QElapsedTimer
, you should consider the overhead of this class.
如果要使用QElapsedTimer
,应该考虑这个类的开销。
For example, the following code run on my machine:
例如,以下代码在我的机器上运行:
static qint64 time = 0;
static int count = 0;
QElapsedTimer et;
et.start();
time += et.nsecsElapsed();
if (++count % 10000 == 0)
qDebug() << "timing:" << (time / count) << "ns/call";
gives me this output:
给我这个输出:
timing: 90 ns/call
timing: 89 ns/call
...
You should measure this for yourself and respect the overhead for your timing.
您应该自己衡量这一点,并尊重您的时间开销。
回答by Damien
Expending the previous answers, here is a macro that does everything for you.
扩展以前的答案,这里有一个宏可以为您做所有事情。
#include <QDebug>
#include <QElapsedTimer>
#define CONCAT_(x,y) x##y
#define CONCAT(x,y) CONCAT_(x,y)
#define CHECKTIME(x) \
QElapsedTimer CONCAT(sb_, __LINE__); \
CONCAT(sb_, __LINE__).start(); \
x \
qDebug() << __FUNCTION__ << ":" << __LINE__ << " Elapsed time: " << CONCAT(sb_, __LINE__).elapsed() << " ms.";
And then you can simple use as:
然后你可以简单地使用:
CHECKTIME(
// any code
for (int i=0; i<1000; i++)
{
timeConsumingFunc();
}
)
output:
输出:
onSpeedChanged : 102 Elapsed time: 2 ms.
onSpeedChanged :102 已用时间:2 毫秒。