Accurately print the program running time

Source: Internet
Author: User

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!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.