开发者

Are C time functions dependent on the system clock?

开发者 https://www.devze.com 2023-04-04 08:03 出处:网络
This specifically goes for gmtime() function in C, although if it gets time differently compared to the other time functions I\'d like to know.

This specifically goes for gmtime() function in C, although if it gets time differently compared to the other time functions I'd like to know.

Like 开发者_开发知识库if I change the system time will it mess things up? Will it get the wrong time?


Yes. they are dependent upon the value of the system clock. If you change the system clock you will get different results as that is the only way that it can get the current system time (unless you use something like NTP but you won't find that in any C/C++ standard library).


On windows, the time function calls GetSystemTimeAsFileTime and does some simple calculations to convert it to the CRT time format (seconds since January 1970 UTC). Other time functions (such as gmtime) don't directly operate on the system time; they just convert between different formats - often one originally obtained by calling time.


As the signature and the name implies:

struct tm * gmtime ( const time_t * timer );

This function converts time_t to tm as UTC time. Keep in mind to uses the value pointed by timer to fill a tm structure with the values that represent the corresponding time, expressed as UTC (or GMT timezone).

#include <stdio.h>
#include <time.h>


int main ()
{
  time_t rawtime;
  struct tm * ptm;

  time ( &rawtime );

  ptm = gmtime ( &rawtime );

  return 0;
}


Yes, several are, one particular one I can think of is the Posix Pthread function pthread_cond_timedwait() will not work if the system clock is not initialized. You need to understand the nuances of how all functions behave and how they may depend on time and Locale of the system, and also the clock drift of your system ...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号