c++ - clock_t是否计算所有线程、c++、pthreads的时间?

标签 c++ benchmarking

假设我的代码由 main() 组成,在 main 中我调用了 2 个并行运行的线程。

假设 main 需要 5 秒才能完成,每个线程需要 10 秒才能完成。

如果我使用 clock_t 为主程序计时,假设 2 个线程并行运行,则程序实际花费的时间为 15 秒。

现在,如果我使用 clock_t 计时,它会给我 15 秒还是 25 秒的时间?

虽然线程 1 和线程 2 并行运行,但 clock_t() 是否会计算线程 1 和线程 2 使用的每个周期并返回使用的周期总数?

我使用 Windows mingw32 和 pthreads。

示例代码:

main(){
 clock_t begin_time ;

  for (unsigned int id = 0; id < 2; ++id)
  {
     pthread_create(&(threads[id]), NULL, thread_func, (void *) &(data[id]));
  }


  for (unsigned int id = 0; id < 2; ++id)
  {
      pthread_join(threads[id], NULL);
  }

time = double( clock () - begin_time )/CLOCKS_PER_SEC;
}

最佳答案

函数 clock 在不同的实现中做不同的事情(特别是在不同的操作系统中)。 clock Windows 中的函数给出了程序启动时的时钟滴答数,与线程数无关,也与机器是否忙碌无关[我相信这个设计决定源于 DOS 和 Windows 2.x 的远古时代是流行的东西,操作系统没有办法“不运行”某些东西]。

在 Linux 中,它给出了使用的 CPU 时间,据我所知,所有类 Unix 操作系统都是如此。

编辑澄清:我的 Linux 系统是这样说的:

In glibc 2.17 and earlier, clock() was implemented on top of times(2). For improved precision, since glibc 2.18, it is implemented on top of clock_gettime(2) (using the CLOCK_PROCESS_CPUTIME_ID clock).

换句话说,时间是给进程的,而不是给当前线程的。

如果您使用的是 Windows,要获取您的进程使用的实际 CPU 时间,您可以(并且应该)使用 GetProcessTimes

关于c++ - clock_t是否计算所有线程、c++、pthreads的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32411678/

相关文章:

c++矩阵重载不起作用

c++ - 无法迭代存储在智能指针中的数组

c++ - 0x76b1dd74 处未处理的异常。访问冲突写入位置 0x00000000

scala - 可以在对的 Seq 上更快地实现 reduceByKey 吗?

julia - 为什么我在 Julia 中的代码随着迭代次数的增加而变慢?

go - 访问基准测试结果

c++ - 使用 C++ 引用此函数的正确方法是什么?

c++再次初始化非指针对象

Git difftool 在 Cygwin/MinGW 中慢得离谱

benchmarking - OpenAI Gym 和 Gazebo 来测试机器人的 RL 算法?