程序中獲取精確的時間,有時是非常必要的。常用的是,在測試程序的性能時,需要使用到精確的時間計時。或者其他情況要用到精確的時間。這就要用到一個函數QueryPerformanceCounter()。用法是從第一次調用QueryPerformanceCounter(),過一段時間後再次調用該函數結束的.兩者之差除以QueryPerformanceFrequency()的頻率就是開始到結束之間的秒數。由於計時函數本身是要耗費很少的時間,所以但一般忽略不計。
有一點要注意的是,如果在多處理器的電腦上使用這個函數需要,需要指定調用的處理器。因為在不同的處理器上會得到不同的結果。
下面的類可以實現該功能。
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;//開始時間
private long endTime = 0;//結束時間
private long frequency= 0;//處理器頻率
public long BegintTime
{
get{return begintTime;}
}
public long EndTime
{
get{return endTime;}
}
public long Frequency
{
get{return frequency;}
}
public QueryPerformance()
{
QueryPerformanceFrequency(frequency)//獲取頻率
}
public void Start()
{
QueryPerformanceCounter(begintTime);
}
public void Stop(bool showRecord)
{
QueryPerformanceCounter(endTime);
if (showRecord)
{
Console.WriteLing(string.Format("用時:{0}s", TastTime));
}
}
public double TastTime//花費時間:單位S
{
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;//開始時間
private long endTime = 0;//結束時間
private long frequency= 0;//處理器頻率
public long BegintTime
{
get{return begintTime;}
}
public long EndTime
{
get{return endTime;}
}
public long Frequency
{
get{return frequency;}
}
public QueryPerformance()
{
QueryPerformanceFrequency(frequency)//獲取頻率
}
public void Start()
{
QueryPerformanceCounter(begintTime);
}
public void Stop(bool showRecord)
{
QueryPerformanceCounter(endTime);
if (showRecord)
{
Console.WriteLing(string.Format("用時:{0}s", TastTime));
}
}
public double TastTime//花費時間:單位S
{
get
{
if(frequency>0)
return (double)(endTime - begintTime) / frequency;
else
return 0;
}
}
}
調用:
QueryPerformance queryPerformance = new QueryPerformance();
QueryPerformance.Start();
//代碼塊、函數等
QueryPerformance.Stop(true);
摘自 白楊樹