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.