在多线程程序中,时钟函数是如何在幕后工作的?

How does the clock function work behind the scene in a multithreading program?

clock 函数在多线程程序中如何在幕后工作?

A​​FAIK,C 标准库提供的时钟函数可以用来测量 运行ning 程序消耗的 CPU 时间,但这个过程在幕后是如何工作的?底层硬件定时器是CPU芯片的一部分吗?如果不是,时钟如何知道 CPU 何时安排到 运行 当前程序?由于clock函数只记录了执行当前程序的每个个体CPU的时间消耗。这意味着在多线程程序中,返回值将低于挂钟时间。

*虽然我在What's the relationship between the real CPU frequency and the clock_t in C?提出了另一个问题,但实际上,这是两个不同的话题,所以,我不想把它们混为一谈post。

Since the clock function only records the time consumption of each individual CPU that executes the current program. Meaning in a multi-threaded program, the returned value would be lower than the wall-clock time.

我在 C 标准中找不到明确的陈述,但是,according to cppreference(通常非常可靠),你的假设是错误的,clock() 函数 returns 总计(对于所有 CPU)程序使用的处理器时间(粗体强调我的):

… For example, if the CPU is shared by other processes, 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, clock time may advance faster than wall clock.