C# 高精度延迟代码执行时间(us/ns)
在上图我们可以看见有这样一个传址参数
long duetime = -10 * us;
原参数类型为 LARGE_INTEGER
定义是用long而不是double
表示需要延迟的时间 它是以100纳秒为一单位
你给1表示100纳秒 是该函数可接最低时钟周期
CreateWaitableTimer // 创建可等待计时器
SetWaitableTimer // 启动可等待计时器
MsgWaitForMultipleObjects // 等待内核对象或消息
CloseHandle // 关闭内核对象
示例代码:
public static void Main()
{
UsDelay(5); // 5us
}
public static void UsDelay(int us)
{
long duetime = -10 * us;
int hWaitTimer = CreateWaitableTimer(NULL, true, NULL);
SetWaitableTimer(hWaitTimer, ref duetime, 0, NULL, NULL, false);
while (MsgWaitForMultipleObjects(1, ref hWaitTimer, false, Timeout.Infinite, QS_TIMER));
CloseHandle(hWaitTimer);
} [DllImport("kernel32.dll")]
public static extern int CreateWaitableTimer(int lpTimerAttributes, bool bManualReset, int lpTimerName);
[DllImport("kernel32.dll")]
public static extern bool SetWaitableTimer(int hTimer, ref long pDueTime,
int lPeriod, int pfnCompletionRoutine, // TimerCompleteDelegate
int lpArgToCompletionRoutine, bool fResume);
[DllImport("user32.dll")]
public static extern bool MsgWaitForMultipleObjects(uint nCount, ref int pHandles,
bool bWaitAll, int dwMilliseconds, uint dwWakeMask);
[DllImport("kernel32.dll")]
public static extern bool CloseHandle(int hObject);
public const int NULL = 0;
public const int QS_TIMER = 0x10;
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/70981.html