写代码时,经常会计算某一段代码的运行时间,以下提供一个微秒级别的类供参考
class CTimeCost
{
public:
CTimeCost(const string &str)
: m_str(str)
{
QueryPerformanceFrequency(&m_freg);
QueryPerformanceCounter(&m_begin);
} ~CTimeCost()
{
LARGE_INTEGER end;
QueryPerformanceCounter(&end);
__int64 nTick = (end.QuadPart - m_begin.QuadPart) * * / m_freg.QuadPart; int len = ;
char *buf = new char[len + ];
memset(buf, , len + );
sprintf_s(buf, len, "\n%s cost %ld微秒\n", m_str.c_str(), nTick); OutputDebugStringA(buf);
cout << buf << endl; delete[]buf;
buf = NULL;
} private:
string m_str;
LARGE_INTEGER m_begin;
LARGE_INTEGER m_freg;
};
//使用方法
void TestTimeCost()
{
{
CTimeCost once("this block cost");
Sleep();
} cout << "other code run" << endl;
}