Windows上C语言中的硬件计时器

时间:2018-10-22 13:01:13

标签: c timer hardware

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

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

1 个答案:

答案 0 :(得分:1)

尝试使用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);
}