cubuntutimeposixglibc

How can clock() from time.h be implemented via times without conversion if returned time units are different?


I wanted to find the implementation of clock in glibc to understand how it works and hopefully find information about its resolution.

I've forund the source code for clock, and it turns out that it just calls __times and returns the sum of tms_utime and tms_stime:

https://codebrowser.dev/glibc/glibc/sysdeps/posix/clock.c.html

/* Return the time used by the program so far (user time + system time).  */
clock_t
clock (void)
{
  struct tms buf;
  if (__times (&buf) < 0)
    return (clock_t) -1;
  return buf.tms_utime + buf.tms_stime;
}

Now, the problem is that to obtain time in seconds, you have to divide the value returned by clock by CLOCKS_PER_SEC, and to get time in seconds from times (which is an alias for __times as I understand), you have to divide tms_utime and tms_stime by sysconf(_SC_CLK_TCK), which are two different values for me (1000000 and 100). So, is this not the implementation I was looking for? Or am I misundertanding something?


Solution

  • This was not the correct implementation. As @n.m.couldbeanAI pointed out, the implemenatation I'm intertested in is located at sysdeps/unix/sysv/linux/clock.c (not sysdeps/posix/clock.c I linked initially) and uses time provided by clock_gettime multiplied by CLOCKS_PER_SEC (as expected):

    https://codebrowser.dev/glibc/glibc/sysdeps/unix/sysv/linux/clock.c.html

    clock_t
    clock (void)
    {
      struct __timespec64 ts;
      _Static_assert (CLOCKS_PER_SEC == 1000000,
              "CLOCKS_PER_SEC should be 1000000");
      if (__glibc_unlikely (__clock_gettime64 (CLOCK_PROCESS_CPUTIME_ID, &ts) != 0))
        return (clock_t) -1;
      return (ts.tv_sec * CLOCKS_PER_SEC
          + ts.tv_nsec / (1000000000 / CLOCKS_PER_SEC));
    }
    

    In short, clock is not implemented via times on my system, so there is no problem with sysconf(_SC_CLK_TCK) and CLOCKS_PER_SEC being different.