我希望计算API返回值所需的时间.

  #include <ctime>
  #include <iostream>

  using namespace std;

  int main(int argc, char** argv) {

      clock_t start;
      double diff;
      start = clock();
      diff = ( std::clock() - start ) / (double)CLOCKS_PER_SEC;
      cout<<"printf: "<< diff <<'\n';

      return 0;
  }

以上代码以秒为单位给出时间.如何在纳秒内以更高的精度达到同样的效果?

推荐答案

其他人发布的关于在循环中重复运行函数的内容是正确的.

For Linux (and BSD) you want to use clock_gettime().

#include <sys/time.h>

int main()
{
   timespec ts;
   // clock_gettime(CLOCK_MONOTONIC, &ts); // Works on FreeBSD
   clock_gettime(CLOCK_REALTIME, &ts); // Works on Linux
}

For windows you want to use the QueryPerformanceCounter. And here is more on QPC

Apparently there is a known issue with QPC on some chipsets, so you may want to make sure you do not have those chipset. Additionally some dual core AMDs may also cause a problem. See the second post by sebbbi, where he states:

QueryPerformanceCounter()和

EDIT 2013/07/16:

在某些情况下,QPC的疗效似乎存在一些争议,如http://msdn.microsoft.com/en-us/library/windows/desktop/ee417693(v=vs.85).aspx所述

...而QueryPerformanceCounter和QueryPerformanceFrequency通常会调整

然而,这个答案https://stackoverflow.com/a/4588605/34329表明,在Win XP service pack 2之后,QPC应该可以在任何MS操作系统上正常工作.

本文显示,Windows 7可以确定处理器是否具有不变的TSC,如果没有,则返回到外部计时器.http://performancebydesign.blogspot.com/2012/03/high-resolution-clocks-and-timers-for.html个跨处理器同步仍然是一个问题.

其他与计时器有关的精细读数:

有关更多详细信息,请参阅 comments .

C++相关问答推荐

%p与char* 等组合缺少的GCC Wform警告

为什么在C中设置文件的位置并写入文件,填充空字符?

丑陋的三重间接:可扩展的缓冲区管理 struct

如何在IF语句中正确使用0.0

为什么内核使用扩展到前后相同的宏定义?

如果我释放其他内容,返回值就会出错

非正规化边缘毛刺

如何将常量char*复制到char数组

初始变量重置后,char[]的赋值将消失

为什么指针运算会产生错误的结果?

无法访问共享目标文件内的共享指针

将变量或参数打包到 struct /联合中是否会带来意想不到的性能损失?

C将数组传递给函数以修改数组

C语言中的数字指针

合并对 struct 数组进行排序

GetText不适用于包含国际字符的帐户名称

C: NULL>;NULL总是false?

struct 中的qsort,但排序后的 struct 很乱

C 错误:对 int 数组使用 typedef 时出现不兼容的指针类型问题

cs50拼写器分配中的无限循环