QT获取UTC时间、windows下获取精确耗时、linux下获取精确耗时
程序员文章站
2022-03-09 21:52:26
...
QT获取UTC时间:
QDateTime origin_time = QDateTime::fromString("1970-01-01 08:00:00","yyyy-MM-dd hh:mm:ss");
QDateTime current_time = QDateTime::currentDateTime();//显示时间,格式为:年-月-日 时:分:秒 周几
qint64 nSeconds = origin_time.secsTo(current_time);//获取距离1970-01-01 08:00:00的总秒数
qint64 nMilliseconds = current_time.time().msec();//获取毫秒数
windows下获取精确耗时:
首先写一个计算耗时的类:
#include <windows.h>
class chronograph
{
public:
chronograph()
{
QueryPerformanceFrequency(&m_freq);
QueryPerformanceCounter(&m_bgn);
}
void start()
{
QueryPerformanceCounter(&m_bgn);
}
double duration()
{
QueryPerformanceCounter(&m_end);
return (m_end.QuadPart - m_bgn.QuadPart) * 1000.0 / m_freq.QuadPart;
}
LARGE_INTEGER now()
{
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
return now;
}
double DoubleNow()
{
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
return now.QuadPart*1000.0 / m_freq.QuadPart;
}
private:
LARGE_INTEGER m_freq;
LARGE_INTEGER m_bgn;
LARGE_INTEGER m_end;
};
使用方法:
chronograph calcuTime;
calcuTime.start();
//耗时的操作······
double nUsetime = calcuTime.duration();//计算出来的耗时
Linux下获取精确耗时的方法:
#include <time.h>
struct timespec time1,time2;
clock_gettime(CLOCK_MONOTONIC,&time1);//开始计时
Sleep(10);//需要计时的操作
clock_gettime(CLOCK_MONOTONIC,&time2);//结束计时
double usetime = (time2.tv_sec-time1.tv_sec)*1000.0+(time2.tv_nsec-time1.tv_nsec)/1000000.0;//计算耗时,单位为ms
上一篇: 五种单例设计模式以及反射攻击改进