When writing a program, it is often necessary to calculate the time required for a certain program to run. Generally, GetCurrentTime is used to calculate the time difference, but the time obtained by this function is not prepared, its precision is also millisecond-level, so the test program running time is only about a time. To obtain microsecond-level precision, you can use the functions QueryPerformanceCounter and QueryPerformanceFrequency. These two functions are counted based on CPU clicks. To facilitate code writing, use the constructor of the C ++ class and the features of the destructor to write a class that prints the code runtime.
Class CPrintfCodeTime
{
Public:
CPrintfCodeTime (const char * vCodeName)
{
M_strName = (NULL! = VCodeName )? VCodeName :"";
LARGE_INTEGER tTimer;
QueryPerformanceCounter (& tTimer );
M_llTime = tTimer. QuadPart;
}
~ CPrintfCodeTime (void)
{
LARGE_INTEGER tTimer;
QueryPerformanceCounter (& tTimer );
Double dbTime = double (tTimer. QuadPart-m_llTime );
// Obtain the CPU frequency
QueryPerformanceFrequency (& tTimer );
DbTime = dbTime/tTimer. QuadPart;
M_strRunCode + = vCode;
Char tBuf [100] = {0 };
# Ifndef _ BORLANDC __
// Output debugging information
Sprintf_s (tBuf, "RunTime: %. 3f millisecond \ n", dbTime * 1000 );
# Else
Sprintf (tBuf, "running time: %. 3f millisecond \ n", dbTime * 1000 );
# Endif
M_strName + = tBuf;
OutputDebugString (m_strName.c_str ());
M_strName.clear ();
}
String m_strName;
LONGLONG m_llTime;
};
This article is from the "Amu Xue" blog and will not be reproduced!