首页 > 代码库 > windows下C++高精度计时

windows下C++高精度计时

写代码时,经常会计算某一段代码的运行时间,以下提供一个微秒级别的类供参考

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) * 1000 * 1000 / m_freg.QuadPart;            int len = 2048;            char *buf = new char[len + 1];            memset(buf, 0, len + 1);            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(1); } cout << "other code run" << endl; }

 

windows下C++高精度计时