Get high precision time difference in C + +

Source: Internet
Author: User

There are usually a number of ways to solve a problem, and we always want to find the most efficient, so we need to compare the time that the different algorithms perform. Unfortunately, the methods provided in C + + generally can only be accurate to the millisecond level.

Provide a more precise approach. Write a function that can be written in C + +:

__declspec (naked) unsigned __int64 getcpucycle (void)

{

_asm

{

Rdtsc

Ret

}

}

The return value of the RDTSC is stored in edx eax, edx is 32 digits high, and eax is low 32 digits. Here the RDTSC instruction (Read time Stamp Counter) obtains the CPU's high-precision timestamp.

This allows us to get the number of time periods since the current CPU has been on the go:

unsigned __int64 icpucycle = Getcpucycle ();

Based on this number, we can calculate the amount of time (in seconds s) that has been spent on the power:

Second = Icpucycle/cpu frequency ratio (HZ);

1GHZ = 1,000 MHZ = 1,000,000 KHZ = 1,000,000,000 HZ;

Get a two-time difference to get the run time. In fact, there is no need to convert time, pay attention to the difference on the line.

Ps:

You can rest assured that a unsigned __int64 will not overflow-you can calculate how many years your CPU can be saved.

According to this method has several advantages: one is high precision, the second is the minimum cost of function calls, the third is a small platform limit, four is the CPU with the corresponding direct relationship ... However, due to high precision, the number of the resulting fluctuations is relatively large.

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.