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

标签 c operating-system clock

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

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

*虽然我在What's the relationship between the real CPU frequency and the clock_t in C?提出了另一个问题,但实际上,这是两个不同的主题,因此,我不想在一篇文章中将它们混为一谈。

最佳答案

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() 函数返回程序使用的(对于所有 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.

关于c - 在多线程程序中,时钟函数是如何在幕后工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70639995/

相关文章:

c++ - 为什么 main() 的参数不是 const 限定的?

java - 我的数字时钟不工作

javascript - 为什么我的 javascript 时钟不工作?

c - 在 C 中打印 char[] 的一部分的最简单方法

c++ - 如何解析以下字符串

c - Microblaze 交叉编译器找不到 clock_gettime

c - 在 malloc 和 free 调用期间如何分配和释放物理页面?

java - 通过 Java servlet 检测操作系统或计算机名称

JavaScript - 在倒计时期间禁用点击功能

c - 如何在另一种类型的函数中使用一种类型的函数?