>>108834817
/*
* Bit fields within a clockid:
*
* The most significant 29 bits hold either a pid or a file descriptor.
*
* Bit 2 indicates whether a cpu clock refers to a thread or a process.
*
* Bits 1 and 0 give the type: PROF=0, VIRT=1, SCHED=2, or FD=3.
*
* A clockid is invalid if bits 2, 1, and 0 are all set.
*/
I don't think many people know this and it's very poorly documented, but you can also get CPU time for any process or thread through these clock_gettime.
#include <time.h>
#include <unistd.h>
#include <stdio.h>
int main() {
//pid_t pid = getpid();
pid_t pid = 1;
clockid_t clk = ((~pid) << 3) | 2;
struct timespec t;
clock_gettime(clk, &t);
printf("cputime for pid 1: %f\n", t.tv_sec + 1e-9 * t.tv_nsec);
return 0;
}
>>108836861
Some arches don't have it, and the vDSO overhead is incredibly low. clock_gettime(CLOCK_MONOTONIC) usually takes less than 60ns, and it's even better if you do the vDSO directly instead of the glibc wrapper.