方法一【相对方法二精度更高,也更稳定些】
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 20; i++)
{
double result = delayUs(0.005);//延时0.005ms,即5us
Console.WriteLine(result);
}
Console.ReadLine();
}
/// <summary>
/// 微秒延时
/// </summary>
/// <param name="time">延时时间,单位:ms</param>
/// <returns></returns>
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;
}
}
}
运行结果:【我又测试了1000次,后边基本可以稳定在0.005(还是比较稳的)】
方法二【不太稳定,5us时精度很差】
using System;
using System.Runtime.InteropServices;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
System.Diagnostics.Stopwatch stopTime = new System.Diagnostics.Stopwatch();
stopTime.Start();
for (int i = 0; i < 20; i++)
{
delayUs(5);//延时即5us,0.005ms
Console.WriteLine(stopTime.Elapsed.TotalMilliseconds);
}
Console.WriteLine("测试结束");
Console.ReadLine();
}
[DllImport("kernel32.dll")]
extern static short QueryPerformanceCounter(ref long x);
[DllImport("kernel32.dll")]
extern static short QueryPerformanceFrequency(ref long x);
/// <summary>
/// 微秒延时
/// </summary>
/// <param name="delay_Time">延时时间,单位:us</param>
public static void delayUs(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;
}
}
}
}
运行结果【延时5us时】:
运行结果【延时500us时】: