假设我的代码由 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/