首页
社区
课程
招聘
[原创]Windows realize 0.5ms timer or Sleep(0.5)
发表于: 2012-1-17 17:33 2250

[原创]Windows realize 0.5ms timer or Sleep(0.5)

2012-1-17 17:33
2250
you can realize 0.5 millisecond sleep; just like  
Sleep(0.5) in windows ; or usleep(500); in UNIX or linux;
//
the key is two point,
first is use a undocument function: NtSetTimerResolution;
second is use a Winsock2 function: select() , like waitForSingleObject();

{
HMODULE hl = LoadLibraryA( "ntdll.dll" );

tNtQueryTimerResolution NtQueryTimerResolution;
tNtSetTimerResolution NtSetTimerResolution;

NtQueryTimerResolution = (tNtQueryTimerResolution)GetProcAddress(hl, "NtQueryTimerResolution");
if( !NtQueryTimerResolution ) return;
NtSetTimerResolution = (tNtSetTimerResolution)GetProcAddress(hl, "NtSetTimerResolution");
if( !NtSetTimerResolution ) return;

ULONG minr, maxr, actr;
DWORD s = NtQueryTimerResolution( &minr, &maxr, &actr );
NtSetTimerResolution(maxr, TRUE, &actr );
}

//code only for demo, may not succeed to compile
{
//initialize part
   WORD wVersionRequested;
WSADATA wsaData;
int err;

/* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
wVersionRequested = MAKEWORD(2, 2);

err = WSAStartup(wVersionRequested, &wsaData);
if (err != 0) {
/* Tell the user that we could not find a usable */
/* Winsock DLL. */
printf("WSAStartup failed with error: %d\n", err);
return 1;
}

   SOCKET sck;
   if((sck=socket(AF_INET,SOCK_STREAM,0))==SOCKET_ERROR)  
  {  
  ShowMessage( "SOCKET error ");  
  closesocket(sck);  
  WSACleanup();  
  }  

//Sleep part
  fd_set FdRead;  
  FD_ZERO(&FdRead);  
  FD_SET(sck,&FdRead);  

  timeval watchDog;
watchDog.tv_sec= 0;
watchDog.tv_usec= 500;

result = select(sck+1, &fd, NULL, NULL, &watchDog);
if (result < 0) test= WSAGetLastError();

//end part
   closesocket(sc);  
  WSACleanup();
}

[培训]内核驱动高级班,冲击BAT一流互联网大厂工作,每周日13:00-18:00直播授课

收藏
免费 0
支持
分享
最新回复 (0)
游客
登录 | 注册 方可回帖
返回
//