开发者

How to get the fractional part of the seconds in UTCTime using time.h

I want to get the system time including fractional part of the seconds. Is it possible in standard c (ANSI C)? If not then tell me some libraries for window OS so that I make it possible. In Linux I have the following code with work fine for me.

 #include <sys/time.h>                                                                
 #include <time.h>                                                                    
 #include <stdlib.h>                                                                  
 #include <stdio.h>                                                                  

 int main(void)                                                                       
 {                                                                                    
   char buffer[30];                                                                   
   struct timeval tv;                                                                 

   time_t curtime;                                                                    



   gettimeofday(&tv, NULL);                                                           
   curtime=tv.tv_sec;                                                                 

   strftime(buffer,30,"%m-%d-%Y  %T.",localtime(&curtime));                           
   printf("%s%ld\n",buffer,tv.tv_usec);                                               

   return 0;                                                                      开发者_开发百科    


   } 

Output is

12-25-2009 11:09:18.35443541

Kindly help me, how is it possible for window OS. IF ANSI C doesn't allow me.


Standard C does not provide sub-second resolution timing.

POSIX does provide sub-second resolution timing - in fact, a number of different ways of doing it, including gettimeofday() which you show.


Like this:

#include <wtypes.h>
int main()
{
    SYSTEMTIME t;
    GetSystemTime(&t);
    int year = t.wYear;
    int month = t.wMonth;
    int day = t.wDay;
    int hour = t.wHour;
    int minute = t.wMinute;
    int second = t.wSecond;
    int second_fraction = t.wMilliseconds;
   return 0;
}

Couple of points about performance if it is important to you:

1) gettimeofday() is quite fast and if is used in a few threads it doesn't cause worsenig of performance

2) Inside localtime() there is a call to pthread_mutex_lock() (probably because it needs some system settings like daytime). So when you use it extensively in a multithreaded application there might performance problems


In the above code

printf("%s%ld\n",buffer,tv.tv_usec);

will work most of the time but it is not correct for small tv.tv_usec values.

If tv.tv_usec is 123, it will print HH:MM:SS.123 when it should print HH:MM:SS.000123

Try this:

printf("%s%.6ld\n", buffer, tv.tv_usec);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜