From: http://www.cppblog.com/guodongshan/archive/2010/10/06/128818.aspx
There are usually many ways to solve a problem. We always want to find the most efficient, so we need to compare differentAlgorithmExecution time. 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,000Hz;
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 ..