1

I know that I can get the current local time by time() function in C.

int main(void)
{
    time_t now = time(NULL);
    struct tm *tm = localtime(&now);
}

However, I want to the insider of the time() function, which means I want to know how the function knows the system time.

In, time.h file, I see that there is defined of the function and it looks like the one below.

time_t time(time_t *);

Thus, I find what time_t is and it is defined like the one below.

typedef __darwin_time_t         time_t;

Finally, __darwin_time_t type is defined like the one below.

typedef long                    __darwin_time_t;  

How the time() function get the current time? Where the code to get the current time of the system?

I'm a beginner of the C programming and wonder how the compiler gets the time.

  • 4
    That depends on the underlying platform (OS and/or HW). The C language standard does not dictate how time-related functionality should be implemented internally under the hood. In most platforms, this function probably makes a low-level system call, to the OS kernel. That is, if there's even an OS to begin with. If not, it may access the HW clock or similar. –  Nov 30 '22 at 15:49
  • Does this answer your question? [Does gettimeofday() on macOS use a system call?](https://stackoverflow.com/questions/40967594/does-gettimeofday-on-macos-use-a-system-call) – Davis Herring Nov 30 '22 at 15:51

1 Answers1

2

Q: I want to know how the function knows the system time.

A: bbbbbbbbb is correct:

That depends on the underlying platform (OS and/or HW). The C language standard does not dictate how time-related functionality should be implemented internally under the hood. In most platforms, this function probably makes a low-level system call, to the OS kernel. That is, if there's even an OS to begin with. If not, they may access the HW clock or similar.

More specifically:

  • Associated with every different C compiler (MS Visual C++, Gnu C/C++, Apache CLang, etc. etc.) for every different platform (Windows, Mac, Linux, embedded system, etc. etc.) is a C runtime library ("CRT").
  • Source code for your particular CRT is often freely available (e.g. from a Google search).
  • If you can find a copy of the C runtime source ... you can see how any given standard C function is implemented (at least for your particular compiler/OS/platform).

Since you're apparently on a Mac, I did a Google search of "time.c opensource.apple.com":

paulsm4
  • 114,292
  • 17
  • 138
  • 190