title: how is clock_gettime implemented on linux?
body: <p>When I <code>strace</code> this:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;time.h&gt;
  
  int main()
  {
    struct timespec ts;
  
    fprintf(stderr, "start!\n");
  
    clock_gettime(CLOCK_REALTIME, &amp;ts);
    fprintf(stderr, "realtime %lu %lu\n", ts.tv_sec, ts.tv_nsec);
  
    clock_gettime(CLOCK_MONOTONIC, &amp;ts);
    fprintf(stderr, "monotonic %lu %lu\n", ts.tv_sec, ts.tv_nsec);
  
    return 0;
  }
  </code></pre>
  
  <p>I get this:</p>
  
  <pre><code>execve("/tmp/x", ["/tmp/x"], [/* 72 vars */]) = 0
  brk(NULL)                               = 0x13d0000
  access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
  mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fed9a0d1000
  access("/etc/ld.so.preload", R_OK)      = -1 ENOENT (No such file or directory)
  open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
  fstat(3, {st_mode=S_IFREG|0644, st_size=126501, ...}) = 0
  mmap(NULL, 126501, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7fed9a0b2000
  close(3)                                = 0
  access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
  open("/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
  read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0&gt;\0\1\0\0\0P\t\2\0\0\0\0\0"..., 832) = 832
  fstat(3, {st_mode=S_IFREG|0755, st_size=1864888, ...}) = 0
  mmap(NULL, 3967488, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7fed99ae5000
  mprotect(0x7fed99ca5000, 2093056, PROT_NONE) = 0
  mmap(0x7fed99ea4000, 24576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1bf000) = 0x7fed99ea4000
  mmap(0x7fed99eaa000, 14848, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7fed99eaa000
  close(3)                                = 0
  mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fed9a0b1000
  mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fed9a0b0000
  mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fed9a0af000
  arch_prctl(ARCH_SET_FS, 0x7fed9a0b0700) = 0
  mprotect(0x7fed99ea4000, 16384, PROT_READ) = 0
  mprotect(0x600000, 4096, PROT_READ)     = 0
  mprotect(0x7fed9a0d3000, 4096, PROT_READ) = 0
  munmap(0x7fed9a0b2000, 126501)          = 0
  write(2, "start!\n", 7start!
  )                 = 7
  write(2, "realtime 1488919932 97097045\n", 29realtime 1488919932 97097045
  ) = 29
  write(2, "monotonic 258985 170149836\n", 27monotonic 258985 170149836
  ) = 27
  exit_group(0)                           = ?
  +++ exited with 0 +++
  </code></pre>
  
  <p>There doesn't seem to be a system call involved in producing either <code>CLOCK_REALTIME</code> or <code>CLOCK_MONOTONIC</code> values. How is this implemented? I tried to step through it in assembler but I must've not noticed the critical part because I can't figure out how it's done.</p>