C#用QueryPerformanceCounter()实现精确定时器
时间:2010-12-22 来源:文@刀
很简单的原理,可是还是搞了半天。希望有大虾们指点指点。
//调用API函数
[DllImport("kernel32.dll")]
extern static short QueryPerformanceCounter(ref long x);
[DllImport("kernel32.dll")]
extern static short QueryPerformanceFrequency(ref long x);
//定义延迟函数
public void delay(long delay_Time)
{
long stop_Value = 0;
long start_Value = 0;
long freq = 0;
long n =0;
QueryPerformanceFrequency(ref freq); //获取CPU频率
long count = delay_Time * freq / 1000;
QueryPerformanceCounter(ref start_Value); //获取初始前值
while ( n<count) //不能精确判定
{
QueryPerformanceCounter(ref stop_Value);//获取终止变量值
n = stop_Value - start_Value;
}