c - how to use clock_gettime -


i trying use clock_gettime function, can't figure out needed headers (or doing wrong if it's not question of headers). code:

#include <stdio.h> #include <unistd.h> /*for clock_realtime? */ #include <time.h>  #define nano_to_milli(n) ((n)/ 1000000)   struct timestruct {     time_t sec;             time_t nano;   };  typedef struct timestruct timestruct;  void gettime (char* _timestr);  int main() {     char* time;     gettime(time);     printf("%s\n", time);      return 0; }   void gettime (char* _timestr) {     time_t milli;     timestruct *curtime;     struct tm* info;      clock_gettime(clock_realtime, curtime);     milli = nano_to_milli(curtime-> m_nano);      info = localtime(&(curtime-> m_sec));     sprintf(_timestr, "%d-%d-%d %d:%d:%d.%d", 1900 + info->tm_year, info->tm_mon, info->tm_mday, info->tm_hour, info->tm_min, info->tm_sec,  (int)milli);  } 

i getting following errors:

implicit declaration of function clock_gettime

clock_realtime undeclared

what missing?

i compiling gcc (linux) ansi , pedantic flags

when compile -ansi, several posix standard functions become unavailable. have access them need compile -std=gnu99. gives c99 plus posix , gnu extensions.

besides that, clock_gettime expects pointer struct timespec, you're supplying custom type instead. rid of custom type , use standard one.

also, pointer you're passing clock_gettime not initialized. function expects parameter point instance of struct timespec. as, function write whatever address uninitialized pointer has. invokes undefined behavior.

instead of creating pointer points nowhere, create struct instance , pass in address.

void gettime (char* _timestr) {     time_t milli;     struct timespec curtime;     struct tm* info;      clock_gettime(clock_realtime, *curtime);     milli = nano_to_milli(curtime.tv_usec);      info = localtime(&curtime.tv_sec);     sprintf(_timestr, "%d-%d-%d %d:%d:%d.%d", 1900 + info->tm_year, info->tm_mon, info->tm_mday, info->tm_hour, info->tm_min, info->tm_sec,  (int)milli);  } 

you're writing uninitialized pointer in main. use char array large enough store string. also, use name other time masks same of system function.

int main() {     char timestr[50];     gettime(timestr);     printf("%s\n", timestr);      return 0; } 

Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -