Time Difference for obtaining high precision in C ++

Source: Internet
Author: User

There are usually multiple ways to solve a problem. We always want to find the most efficient method, so we need to compare the time used for different Algorithm Execution. Unfortunately, the methods provided in C ++ can only be accurate to milliseconds.

Provides a more accurate method. Write a function in C ++ as follows:

_ Declspec (naked) unsigned _ int64 GetCpuCycle (void)

{

_ Asm

{

Rdtsc

Ret

}

}

The returned values of RDTSC are stored in edx eax. EDX is high 32-bit, and EAX is low 32-bit. Here, the RDTSC command (Read Time Stamp Counter) gets the high-precision timestamp of the CPU.

In this way, we can obtain the current number of CPU cycles from power-on everywhere:

Unsigned _ int64 iCpuCycle = GetCpuCycle ();

Based on this number, we can calculate the time (s) that has elapsed since power-on ):

Second = iCpuCycle/CPU clock speed (HZ );

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

You can get the running time by getting the difference twice. In fact, there is no need to convert it into time, just pay attention to the difference.

PS:

You can rest assured that an unsigned _ int64 will not overflow--you can calculate how many years your CPU can be stored ..

There are several advantages based on this method: First, high precision, second, minimum function call overhead, third, low platform limitations, and fourth, there is a direct relationship with CPU clock speed... However, due to the high precision, the numbers are relatively large.

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.