请问有那些精确的不占用CPU的延时方法,最好使用硬件时钟延时

ThinkX 2005-07-26 05:50:16
和Sleep一样的效果,能使线程暂停指定一段时间,不占用CPU,精度1ms之内,重要的是,受CPU占用率的影响要小。

我用
int _tmain(int argc, _TCHAR* argv[])
{
DWORD start = GetTickCount();
int count = 0;
while (true)
{
if (GetTickCount() - start > 10000)
break;

Sleep(1);
count++;
}

std::cout << "Count : " << count << std::endl;
std::cin.get();
return 0;
}
发现,在CPU空闲时执行,count为5000左右,也就是说Sleep(1)几乎执行了2ms;而在CPU100%时运行,count为3000左右,也就是Sleep(1)延时了3ms,很不稳定。
...全文
480 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
AntonlioX 2005-07-26
  • 打赏
  • 举报
回复
up
ThinkX 2005-07-26
  • 打赏
  • 举报
回复
OK,谢谢了,看了SetWaitableTime的精确度很高,低于1ms,而且无消耗等待,给分。
NowCan 2005-07-26
  • 打赏
  • 举报
回复
#include <windows.h>
#include <stdio.h>

int main()
{
HANDLE hTimer = NULL;
LARGE_INTEGER liDueTime;

liDueTime.QuadPart=-100000000;

// Create a waitable timer.
hTimer = CreateWaitableTimer(NULL, TRUE, "WaitableTimer");
if (!hTimer)
{
printf("CreateWaitableTimer failed (%d)\n", GetLastError());
return 1;
}

printf("Waiting for 10 seconds...\n");

// Set a timer to wait for 10 seconds.
if (!SetWaitableTimer(
hTimer, &liDueTime, 0, NULL, NULL, 0))
{
printf("SetWaitableTimer failed (%d)\n", GetLastError());
return 2;
}

// Wait for the timer.

if (WaitForSingleObject(hTimer, INFINITE) != WAIT_OBJECT_0)
printf("WaitForSingleObject failed (%d)\n", GetLastError());
else printf("Timer was signaled.\n");

return 0;
}

上面是MSDN的例子,SetWaitableTimer
nelsonc 2005-07-26
  • 打赏
  • 举报
回复
Sleep(1)不是用于定时的,所以你这种用法不正规。
使用SetTimer,或CreateWaitableTimer。
这种方法的误差大概有10几ms。
更准确的定时用软件可能作不到了。

PS. 使用QueryPerformanceCounter可以得到更精确的时间值,但不能用来定时。

15,473

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 进程/线程/DLL
社区管理员
  • 进程/线程/DLL社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧