1

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;
}
Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Eric Stotch
  • 141
  • 4
  • 19
  • Call into the `clock_gettime` implementation in the VDSO, to use code+data exported by the kernel. https://blog.packagecloud.io/the-definitive-guide-to-linux-system-calls/. Since the VDSO is basically an ELF shared library, the infrastructure for getting function-pointers / GOT entries only works automatically in a dynamic executable or library, I think. – Peter Cordes Apr 12 '22 at 22:37
  • For benchmarking on a single system, yeah you just find out what the TSC frequency is, e.g. from `dmesg`, then use `lfence`+`rdtsc` or `rdtscp` – Peter Cordes Apr 12 '22 at 22:40

0 Answers0