KodeWarrior
KodeWarrior

Reputation: 3598

Implementation of clock()

I was going through stackoverflow threads on various mechanisms for computing CPU time of a process.

How is clock() internally implemented ? Does it use rdtsc() ( If that's the case then it is sensitive to migration between cores ).

Also, getrusage() implemented ? Does it also depend on TSC ?

Thanks in advance

Upvotes: 1

Views: 1018

Answers (2)

ash
ash

Reputation: 5155

The kernel keeps track of CPU utilization for processes in sizes of ticks.

Both clock() and getrusage() are both based on these.

Ticks are accumulated by processes by the kernel using a sampling method in which the kernel receives a hardware interrupt for the clock and executes the clock handler, which adds the tick to the currently running process. At least, this is how it worked last time I looked.

So, rtdsc does not come into play at all - which is a good thing since rdtsc does not measure accurately across CPUs.

Upvotes: 2

You could easily glance at some libc code. Here is the time/ directory of musl-libc

On several libraries, some low level timing syscalls are using VDSO to avoid paying the cost of a real syscall (from user-space to kernel and back), so somehow uses RTDSC.

But I am surprised that you ask. If it is curiosity, just study the source code of free software implementation. Otherwise, trust the specifications & the implementations.

Gory details could be complex, since implementation and system specific. The real implementation could be dynamically tuned at run-time (eg thru VDSO set-up in the kernel).

Upvotes: 0

Related Questions