C# 一般很容易实现毫秒延时
1.加入命名空间:using System.Threading;
2.Thread.Sleep(1000); // 1000毫秒延时
C#实现微秒延时方法
1.加入命名空间:using System.Runtime.InteropServices;
2.代码如下:主要用到两个函数QueryPerformanceFrequency()和QueryPerformanceCounter();
[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 / 1000000; //这里写成1000000就是微秒,写成1000就是毫秒
QueryPerformanceCounter(ref start_Value); //获取初始前值
while (n < count) //不能精确判定
{
QueryPerformanceCounter(ref stop_Value);//获取终止变量值
n = stop_Value - start_Value;
}
}
C++延时写法
void Time::LoopDelay(U32 ticks)
{
if (ticks) {
LARGE_INTEGER litmp;
LONGLONG QPart1, QPart2;
double dfMinus, dfFreq, dfTim, dfSleep;
dfSleep = (double)ticks / 1000;
QueryPerformanceFrequency(&litmp);
dfFreq = (double)litmp.QuadPart;// 獲得計數器的時鐘頻率
QueryPerformanceCounter(&litmp);
QPart1 = litmp.QuadPart;// 獲得初始值
do
{
QueryPerformanceCounter(&litmp);
QPart2 = litmp.QuadPart;//獲得中止值
dfMinus = (double)(QPart2 - QPart1);
dfTim = dfMinus / dfFreq;// 獲得對應的時間值,單位為秒k;
} while (dfTim<dfSleep);
}
}