vc++高精度计时sleep

LARGE_INTEGER high_precision_sleep(LARGE_INTEGER preTime, unsigned long long   sleepTime) {
    LARGE_INTEGER t;
    QueryPerformanceCounter(&t);
    
    while(t.QuadPart-preTime.QuadPart<sleepTime)QueryPerformanceCounter(&t);
    //printf("sleepTime=%d\n", t.QuadPart-preTime.QuadPart);//调试时用来观察每次暂停时间。一般应略有不同才正确
    /*//这种方式与直接返回t精度差不多,但多了一个运算,划不来
preTime.QuadPart += sleepTime; return preTime;*/ return t; }

  使用方法:

LARGE_INTEGER freq,t0,t1,t3;

QueryPerformanceFrequency(&freq);//频率   计数/秒

 

//当前频率 TIMES_PER_SECOND 下间隔的计数
auto SLEEP_COUNT = freq.QuadPart / TIMES_PER_SECOND;

 

QueryPerformanceCounter(&t0);
QueryPerformanceCounter(&t3);
for (int i = 0; i < number; i++) {

   //do something

   

   srand(t3.LowPart);//srand()函数产生一个以当前时间开始的随机种子
  Sleep(rand() %20 );//TIMES_PER_SECOND=30,理论上每次Sleep(33.33ms),但不能Sleep(rand()%30),因为Sleep精度问题,可能实际上超过

  //BitBlt(dcMem, 0, 0, 1920, 1080, dcScreen, 0, 0, SRCCOPY);

  t3=high_precision_sleep(t3, SLEEP_COUNT);

}

QueryPerformanceCounter(&t1);

cout << "执行 "<< number << " 次, 耗时 " << (((t1.QuadPart - t0.QuadPart) * 1000000) / freq.QuadPart)<< " 微秒" << std::endl;

 

当TIMES_PER_SECOND=30,number=500时,理论耗时:

 

实际耗时:耗时 16668737 微秒、耗时 16668737 微秒、耗时 16667480 微秒...每次相差不大,在1ms左右

 

posted @ 2021-09-06 12:21  吾非无心  阅读(511)  评论(0编辑  收藏  举报