home *** CD-ROM | disk | FTP | other *** search
/ kermit.columbia.edu / kermit.columbia.edu.tar / kermit.columbia.edu / sredird / telnetcpcd-1.09.tar.gz / telnetcpcd-1.09.tar / timestamp.c < prev    next >
C/C++ Source or Header  |  2003-08-12  |  2KB  |  76 lines

  1. /*
  2.     timestamp.c
  3.  
  4.     Copyright (c) 2002,2003 Thomas J Pinkl <tom@pinkl.com>
  5.  
  6.     Return a timestamp string for the current date and time.
  7.  
  8.     Version 1.00    04/02/1998
  9. */
  10.  
  11. #include "telnetcpcd.h"
  12. #define STRSIZE    32
  13.  
  14. char *timestamp(void)
  15. {
  16.     static char string[STRSIZE];
  17.     static time_t last = 0L;
  18.     time_t seconds;
  19.     struct tm *timeptr;
  20.  
  21.     seconds = time((time_t *) NULL);
  22.     if (seconds == last)                /* time hasn't changed since last */
  23.         return(string);
  24.     last = seconds;                        /* save for next time */
  25.  
  26.     /*
  27.         our string has the format: MMM DD HH:MM:SS
  28.  
  29.         this format is consistent with that of syslog
  30.     */
  31.     timeptr = localtime(&seconds);
  32.     strftime(string,STRSIZE,"%b %d %T",timeptr);
  33.  
  34.     return(string);
  35. }
  36.  
  37.  
  38. /*
  39.     this version includes milliseconds
  40. */
  41. char *timestamp_ms(void)
  42. {
  43.     static char string[STRSIZE];
  44.     static struct timeval last = {0L, 0L};
  45.     struct timeval now;
  46.     struct tm *timeptr;
  47.     char *p;
  48.  
  49.     /*
  50.         gettimeofday() returns seconds and microseconds since the epoch.
  51.  
  52.         we convert microseconds (1,000,000) to milliseconds (1,000) by
  53.         dividing by 1000 because we're not interested in the extra 
  54.         precision.  and doing so allows us to cache the returned string.
  55.     */
  56.     gettimeofday(&now,NULL);
  57.     if ((now.tv_sec == last.tv_sec) && ((now.tv_usec / 1000) == (last.tv_usec / 1000)))
  58.         return(string);                            /* time hasn't changed since last */
  59.     last.tv_sec = now.tv_sec;                    /* save for next time */
  60.     last.tv_usec = now.tv_usec;
  61.  
  62.     /*
  63.         our string has the format: MMM DD HH:MM:SS
  64.  
  65.         this format is consistent with that of syslog
  66.     */
  67.     timeptr = localtime(&(now.tv_sec));
  68.     strftime(string,STRSIZE,"%b %d %T",timeptr);
  69.  
  70.     /* now append milliseconds to the string */
  71.     p = string + strlen(string);                /* points to the null */
  72.     sprintf(p,".%03d",(int) (now.tv_usec / 1000));
  73.  
  74.     return(string);
  75. }
  76.