QueryPerformanceCounter

QueryPerformanceCounter

如何在OS Windows上实现硬件计时器。我需要以毫秒和纳秒为单位来衡量计算。

for (i=0;i<1024;i++){
  //start timer
  //computations
  //end timer
  //printf result(end - start)
}

最佳答案

尝试使用QueryPerformanceFrequencyQueryPerformanceCounter方法来获取亚毫秒级的时间:

LARGE_INTEGER cpu_khz, start_time, end_time;
QueryPerformanceFrequency(&cpu_khz);
for (i=0;i<1024;i++) {
  QueryPerformanceCounter(&start_time);
  // computations
  QueryPerformanceCounter(&end_time);
  double delta_time = (start_time.QuadPart-end_time.QuadPart) / (double)cpu_khz.QuadPart;
  printf("took %.3f seconds", delta_time);
}

09-07 05:00