今天为了检测自己某些功能模块的时间消耗,发现使用了好几种方法,得到的时间都是0 ,后来才发现是因为消耗的时间太少了,一般常用的方法得到的时间精度不够,下面分享一下我的学习历程。
1.一开始使用GetTickCount();,测试结果为0,具体代码:
DWORD dwStart = GetTickCount();
DWORD dwStart = timeGetTime();
m_String=getSystemName().c_str();
DWORD dwUsed = timeGetTime();
m_Time = dwUsed - dwStart;
2.使用 timeGetTime()函数,需要添加#include <Mmsystem.h>,自己测试结果为0
DWORD dwStart = timeGetTime(); //开始时间
m_String=getSystemName().c_str();
DWORD dwUsed = timeGetTime(); //结束时间
m_Time8 = dwUsed - dwStart; //消耗时间
还使用了clock()函数,也不行,最后在网上查到了一个以纳秒计的函数,1秒=10亿纳秒。总算结果测试不为零了。具体代码:
先再头文件内定义一内联函数:
inline unsigned GetCycleCount() { __asm _emit 0x0F __asm _emit 0x31 }
实际使用:
unsigned long t1,t2;
t1 = (unsigned long)GetCycleCount(); //开始时间
m_String = getSystemName().c_str();
t2 = (unsigned long)GetCycleCount();
m_Time = t2-t1;
结果截图: