In some tests, we need to obtain high-precision code execution time to compare the efficiency. Recently, a module has a very short execution time, but the call frequency is very high. Accurately calculating the computing time is very important for improving the overall efficiency of the program.
When I first got in touch with. net, I also wanted to test the running time of the program I wrote. At that time, I used the stupid method to subtract two datetime. Now values. Later I learned that using environment. tickcount is sufficient for General tests. However, it does not have any way to perform high-precision testing. It often returns 0 errors. For high-precision tests, we should use the queryperformancefrequency function and queryperformancecounter function. They provide higher accuracy than environment. tickcount. In fact, environment. tickcount is calling the queryperformancefrequency function and queryperformancecounter function.
The following code is used:
Using system;
Class class1
{
[System. runtime. interopservices. dllimport ("kernel32.dll")]
Static extern bool queryperformancecounter (ref Long Count );
[System. runtime. interopservices. dllimport ("kernel32.dll")]
Static extern bool queryperformancefrequency (ref Long Count );
[Stathread]
Static void main (string [] ARGs)
{
Long Count = 0;
Long count1 = 0;
Long freq = 0;
Double result = 0;
Queryperformancefrequency (ref freq );
Queryperformancecounter (ref count );
// Module to be tested
Queryperformancecounter (ref count1 );
Count = count1-count;
Result = (double) (count)/(double) freq;
Console. writeline ("Time consumed: {0} seconds", result );
Console. Readline ();
}
}
In this way, we can get very accurate results. However, there will always be some errors in the running time of the module, and when the calculation is very accurate, these running time errors are also obvious. For this reason, I tested it cyclically multiple times to make its error average, and analyzed the execution efficiency through the results of Multiple tests.
Using system;
Class class1
{
[System. runtime. interopservices. dllimport ("kernel32.dll")]
Static extern bool queryperformancecounter (ref Long Count );
[System. runtime. interopservices. dllimport ("kernel32.dll")]
Static extern bool queryperformancefrequency (ref Long Count );
[Stathread]
Static void main (string [] ARGs)
{
Long Count = 0;
Long count1 = 0;
Long freq = 0;
Double result = 0;
Queryperformancefrequency (ref freq );
Queryperformancecounter (ref count );
// There is no such loop at the beginning, and the resulting data fluctuates greatly. Add this loop to make the results more even.
For (INT I = 0; I <500; I ++)
{
// Module to be tested
}
Queryperformancecounter (ref count1 );
Count = count1-count;
Result = (double) (count)/(double) freq;
Console. writeline ("Time consumed: {0} seconds", result );
Console. Readline ();
}
}