C++ 中带线程的时钟函数

clock function in C++ with threads

这里有一个非常有趣的注释:http://en.cppreference.com/w/cpp/chrono/c/clock

"Only the difference between two values returned by different calls to std::clock is meaningful, as the beginning of the std::clock era does not have to coincide with the start of the program. std::clock time may advance faster or slower than the wall clock, depending on the execution resources given to the program by the operating system. For example, if the CPU is shared by other processes, std::clock time may advance slower than wall clock. On the other hand, if the current process is multithreaded and more than one execution core is available, std::clock time may advance faster than wall clock."

为什么时钟会随着多线程加速?我正在检查有线程和没有线程的 C++ 程序的性能,我注意到线程的时间相似(不是更好)但 感觉 更快(比如说 8 秒3 秒的运行时间)。

如果有多个核心可用,并且您是 运行 多线程,则可能有多个线程同时在不同的核心上执行。由于 clock() 测量处理器时间,它可能比挂钟时间提前,因为多个线程同时推进它。

正如文档中给出的示例 - 它显示创建了两个线程,报告的 clock() 值几乎是报告的挂钟时间的两倍。