clock_gettime 和 getrusage 有什么关系?

How are clock_gettime and getrusage related?

我想了解 cpu 时间在 Linux 中是如何计算的。特别是,我想把这个问题的重点放在 clock_gettime and on getrusage 上。我想知道这两个有什么关系。

Unix 和 Linux 中有很多时钟。有的是挂钟(CLOCK_REALTIME),有的是改装挂钟(CLOCK_MONO,CLOCK_BOOT),有的是CPU打卡钟(CLOCK_PROCESS_CPUTIME_ID,CLOCK_THREAD_CPUTIME_ID).

clock_gettime 基本上可以从任何分配了 clkid 的时钟中提取。 (在内核中,基本上有代码为每个 clkid 定义一个适当的 get 方法供 clock_gettime 使用。)

我怀疑,但尚未证实,clock_gettime 与 CPU 时间相关的 clkids 之一从与 getrusage 相同的 CPU 计数器中提取.

依次回答您的问题:

Does one call the other one?

我不这么认为。

Do they both rely on the same underlying mechanism?

我相信是的,但我没有证实这一点。

If so what's their greatest common denominator, and by that I mean, what function from the linux kernel are they both calling to get the time?

我不确定。 (抱歉。我在所有这些方面的工作都集中在墙上时间,而不是 CPU 时间。)

And if they are not relying on the same underlying mechanism then why?

因为 Linux 内核中与时间相关的代码非常复杂,并且试图为很多不同的主人服务。