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.