It is sometimes necessary to obtain the exact time in the program. It is often used to test the performance of a program and use accurate time timing. Or in other cases, the exact time is required. This requires a function QueryPerformanceCounter (). The usage starts from the first time QueryPerformanceCounter () is called, and the call ends again after a period of time. The difference between the two is divided by the frequency of QueryPerformanceFrequency (), that is, the number of seconds between the start and the end. Because the timing function itself takes a small amount of time, it is generally ignored.
Note that if you need to use this function on a multi-processor computer, you need to specify the called processor. Because different processors have different results.
The following class can implement this function.
Public class QueryPerformance
{
[DllImport ("Kernel32.dll")]
Private static extern bool QueryPerformanceCounter (out long performanceCount );
[DllImport ("Kernel32.dll")]
Private static extern bool QueryPerformanceFrequency (out long frequency );
Private long begintTime = 0; // start time
Private long endTime = 0; // End Time
Private long frequency = 0; // processor frequency
Public long BegintTime
{
Get {return begintTime ;}
}
Public long EndTime
{
Get {return endTime ;}
}
Public long Frequency
{
Get {return frequency ;}
}
Public QueryPerformance ()
{
QueryPerformanceFrequency (frequency) // obtain the frequency
}
Public void Start ()
{
QueryPerformanceCounter (begintTime );
}
Public void Stop (bool showRecord)
{
QueryPerformanceCounter (endTime );
If (showRecord)
{
Console. WriteLing (string. Format ("Time: {0} s", TastTime ));
}
}
Public double TastTime // time consumed: Unit: seconds
{
Get
{
If (frequency> 0)
Return (double) (endTime-begintTime)/frequency;
Else
Return 0;
}
}
}
Public class QueryPerformance
{
[DllImport ("Kernel32.dll")]
Private static extern bool QueryPerformanceCounter (out long performanceCount );
[DllImport ("Kernel32.dll")]
Private static extern bool QueryPerformanceFrequency (out long frequency );
Private long begintTime = 0; // start time
Private long endTime = 0; // End Time
Private long frequency = 0; // processor frequency
Public long BegintTime
{
Get {return begintTime ;}
}
Public long EndTime
{
Get {return endTime ;}
}
Public long Frequency
{
Get {return frequency ;}
}
Public QueryPerformance ()
{
QueryPerformanceFrequency (frequency) // obtain the frequency
}
Public void Start ()
{
QueryPerformanceCounter (begintTime );
}
Public void Stop (bool showRecord)
{
QueryPerformanceCounter (endTime );
If (showRecord)
{
Console. WriteLing (string. Format ("Time: {0} s", TastTime ));
}
}
Public double TastTime // time consumed: Unit: seconds
{
Get
{
If (frequency> 0)
Return (double) (endTime-begintTime)/frequency;
Else
Return 0;
}
}
}
Call:
QueryPerformance queryPerformance = new QueryPerformance ();
QueryPerformance. Start ();
// Code blocks and functions
QueryPerformance. Stop (true );
From Poplar