How to accurately calculate time to microsecond

Source: Internet
Author: User
Tags time in milliseconds

I,

In Windows, it takes time in milliseconds to obtain the data.

Accurate Time (calculated based on CPU frequency) in Windows)
# Include <windows. h>
# Include <iostream>
(Obtain CPU frequency)
Large_integer T1, T2, feq;
Queryperformancefrequency (& feq); // The number of beats per second
Queryperformancecounter (& T1); // Number of pre-test beats
For (INT I = 0; I <10000; I ++ );
Queryperformancecounter (& T2); // Number of beats after test
Double D = (double) t2.quadpart-(double) t1.quadpart)/(double) feq. quadpart); // time difference second
STD: cout <D <STD: Endl;

Accurate Time in Windows

DWORD gettickcount (void );
SDK: The gettickcount function retrieves the number of milliseconds that have elapsed since Windows was started.

Ctime T = ctime: getcurrenttime ();
SDK: This method obtainsCtimeObject that represents the current time.

 

II,

I initially used the timegettime () function, which can only be accurate to ms. The usage is as follows:

# Include <mmsystem. h>

Dowd begin, end;

Begin = timegettime ();

// The program fragment you want to calculate

End = timegettime ();

Cstring strtime;
Strtime. Format ("% d", end-Start );

Finally, set linker-input-additional dependencies and winmm. Lib in your project.

If you want to display the subtle level, it is not enough. You can use the system counter.

Large_integer frequency;
Queryperformancefrequency (& frequency );

Large_integer start, end;
Queryperformancecounter (& START );
// The program fragment you want to calculate

Queryperformancecounter (& End );

Int time = (end. quadpart-start. quadpart) * 1000000)/frequency. quadpart );

Useful link: http://dev.csdn.net/develop/article/41/41104.shtm

Http://dev.csdn.net/article/74/74169.shtm

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.