检索 C 中两次迭代之间花费的时间

Retrieve time spent between two iterations in C

我有线程运行,线程函数包含一个循环并迭代一定时间。

例如:

void *start(void *p) // This function is called at the thread creation
{
      int i = 0;

      while (i < 10){
          i++;
      }
} // NOTE THAT THIS FUNCTION IS AN EXAMPLE, the iteration can be small or high.

如何监控两次迭代之间花费的时间? (考虑到我同时有很多线程运行)

我听说过clock()函数,下面的操作可以确定两次clock()输出之间花费的时间:

(double)(begin - end) / CLOCKS_PER_SEC;

我如何才能有效地检索此类信息?

我建议使用 POSIX 函数 clock_gettime:

#include <time.h>

timespec real_startTime;
timespec real_endTime;      

// Start time measurement
if(clock_gettime(CLOCK_REALTIME, &real_startTime) != 0)
{
    perror("Error on fetching the start-time");
    exit(EXIT_FAILURE);
}

// Do some long running operation that should be measured

// Stop time measurement
if(clock_gettime(CLOCK_REALTIME, &real_endTime) != 0)
{
    perror("Error on fetching the end-time");
    exit(EXIT_FAILURE);
}

double real_runTime = (real_endTime.tv_sec + real_endTime.tv_nsec / 1000.0 / 1000.0 / 1000.0) - (real_startTime.tv_sec + real_startTime.tv_nsec / 1000.0 / 1000.0 / 1000.0);

与 clock 的区别在于它输出 wall-clock time,"real" 执行某事(包括 I/O 等)的时间。 ), 而不是基于 CPU time.

clock

摘录 clock_gettime 男人:

All implementations support the system-wide realtime clock, which is identified by CLOCK_REALTIME. Its time represents seconds and nanoseconds since the Epoch.

时钟人摘录:

The clock() function returns an approximation of processor time used by the program.


编辑: 正如许多人所建议的那样,您不会在示例代码中遇到任何真正的差异(计算从 0 到 10 的整数),但是如果您测量一些长的 运行 系统,您会遇到 I/O 的系统,等)。