Methods for precise timing of C + + in window

Source: Internet
Author: User

Well, the programmer's eternal quest is performance, right?

In order to measure performance, timing is naturally required.

However, regardless of the C standard library or C + + standard library, the time API accuracy is not high because of commonality . The basic is the millisecond level.

So if you want to really accurately measure the performance of a program, you still have to rely on the system API. The following timing method can be accurate to <1us.

If you do not want to know what the principle, you can directly copy the following simple timer class. Put it in a header file and include it when you use it.

#include <windows.h>class Mytimer{private:large_integer _freq; Large_integer _start; Large_integer _stop;public:mytimer () {queryperformancefrequency (&_freq);} inline void Start () {QueryPerformanceCounter (&_start);} inline void Stop () {QueryPerformanceCounter (&_stop);} Inline double elapse () {return 1e3* (_stop. QuadPart-_start. QuadPart)/_freq. QuadPart;} Inline long Long ticks () {return _stop. QuadPart-_start. QuadPart;}};

The way to use it is simple: three APIs: start, stop, elapse.

Example:        mytimer timer;        Timer.start ();        Matrixxd m3 = m1 * m2;        Critical Code here        timer.stop ();        printf ("Time Elapsed:%lf\n", Timer.elapse ());

The main system API used is as follows two.

QueryPerformanceCounter

From <http://msdn.microsoft.com/en-us/library/windows/desktop/ms644904 (v=vs.85). aspx>

QueryPerformanceFrequency function

From <http://msdn.microsoft.com/en-us/library/windows/desktop/ms644905 (v=vs.85). aspx>

Take a look at MSDN 's instructions.

Methods for precise timing of C + + in window

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.