How does one do a "zero-syscall clock_gettime" without dynamic linking?

801 views Asked by At

I ran the code below with strace. I can see it doesn't use a system call to get the time. After write only clock_nanosleep and exit_group are called. It correctly gives me 3 every run (I was expecting to occasionally get 2).

Musl .80 release says "zero-syscall clock_gettime support (dynamic-linked x86_64 only)"

Is there a way to do this without depending on being dynamically linked? Perhaps with cpuid? Compiling with -nostdlib says it depends on clock_gettime. Is there a way to implement CLOCK_REALTIME or CLOCK_MONOTONIC? I'd find using __rdtsc(p) acceptable if there's a way to get cpu frequency so I can estimate how much time has pass. I don't need nanosecond precision.

#include <time.h>
int main() {
    struct timespec time, time2;
    write(1, "Test\n", 5);
    clock_gettime(CLOCK_REALTIME, &time);
    sleep(3);
    clock_gettime(CLOCK_REALTIME, &time2);
    return time2.tv_sec - time.tv_sec;
}
0

There are 0 answers