这里有两种方法,都有些许误差。可以自己把握。
第一种:
/*
功能:微秒延时(1000us == 1ms)
参数:延时时间单位ms
延时5us:delayUs(0.005);
*/
public static double delayUs(double time)
{
System.Diagnostics.Stopwatch stopTime = new System.Diagnostics.Stopwatch();
stopTime.Start();
while (stopTime.Elapsed.TotalMilliseconds < time) { }
stopTime.Stop();
return stopTime.Elapsed.TotalMilliseconds;
}
第二种:
/*
功能:微秒延时(1000us == 1ms)
参数:延时时间单位us
延时5us:delayUs(5);
*/
[DllImport("kernel32.dll")]
extern static short QueryPerformanceCounter(ref long x);
[DllImport("kernel32.dll")]
extern static short QueryPerformanceFrequency(ref long x);
//定义延迟函数
public void USdelay(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 / 1000000; //这里写成1000000就是微秒,写成1000就是毫秒
QueryPerformanceCounter(ref start_Value); //获取初始前值
while (n < count) //不能精确判定
{
QueryPerformanceCounter(ref stop_Value);//获取终止变量值
n = stop_Value - start_Value;
}
}