• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 538
  • Last Modified:

time diff

The following code displays the current time. It does not display milliseconds.

I am looking to do something like:

// Note the time_1

Do Something

// Note the time_2

// compute the time diff time_2 - time_1
I want granularity in milliseconds.

time_t rawtime;
        struct tm * timeinfo;
        time(&rawtime );
        timeinfo = localtime ( &rawtime );
        printf ( "Current local time and date: %s", asctime (timeinfo) );

Open in new window

0
learningunix
Asked:
learningunix
  • 7
  • 4
  • 2
2 Solutions
 
learningunixAuthor Commented:
0
 
phoffricCommented:
difftime: "Calculates the difference in seconds between time1 and time2."
0
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

 
phoffricCommented:
You can consider using gettimeofday() which uses struct timeval     http://www.opengroup.org/onlinepubs/000095399/functions/gettimeofday.html
0
 
phoffricCommented:
I found an example:     http://souptonuts.sourceforge.net/code/gettimeofday.c.html
/* C routine: sample gettimeofday with time in milliseconds
   mmc mchirico@users.sourceforge.net

   Downloads:
   http://prdownloads.sourceforge.net/cpearls/date_calc.tar.gz?download

*/
#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;

Open in new window

0
 
jkrCommented:
If you want to measure execution time, 'clock()' (http://www.manpagez.com/man/3/clock/) might be more what you are looking for
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// ...

   clock_t start, finish;
   double  duration;

   /* Measure the duration of an event. */
   start = clock();

   /* Do Something */   

   finish = clock();
   duration = (double)(finish - start) / CLOCKS_PER_SEC;
   printf( "%f seconds\n", duration );

Open in new window

0
 
phoffricCommented:
Here is a discussion of Elapsed Time using GNU C
    http://www.gnu.org/s/libc/manual/html_node/Elapsed-Time.html
Shown below is source code from this link.
Depending on the range of your time difference, this approach may be needed.
     /* Subtract the `struct timeval' values X and Y,
        storing the result in RESULT.
        Return 1 if the difference is negative, otherwise 0.  */
     
     int
     timeval_subtract (result, x, y)
          struct timeval *result, *x, *y;
     {
       /* Perform the carry for the later subtraction by updating y. */
       if (x->tv_usec < y->tv_usec) {
         int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
         y->tv_usec -= 1000000 * nsec;
         y->tv_sec += nsec;
       }
       if (x->tv_usec - y->tv_usec > 1000000) {
         int nsec = (x->tv_usec - y->tv_usec) / 1000000;
         y->tv_usec += 1000000 * nsec;
         y->tv_sec -= nsec;
       }
     
       /* Compute the time remaining to wait.
          tv_usec is certainly positive. */
       result->tv_sec = x->tv_sec - y->tv_sec;
       result->tv_usec = x->tv_usec - y->tv_usec;
     
       /* Return 1 if result is negative. */
       return x->tv_sec < y->tv_sec;
     }

Open in new window

0
 
learningunixAuthor Commented:
I keep getting cannot open include files <sys/time.h> on my windows platform
0
 
phoffricCommented:
Hi learningunix,
Hmm, for some reason, I thought you were learning on a Unix platform. Not sure how I jumped to that conclusion. What compiler are you using?
    Paul
0
 
jkrCommented:
Have you tried 'clock()' as above? That will work on Wondows, too. Alternatively, 'GetTickCount()' (http://msdn.microsoft.com/en-us/library/ms724408%28VS.85%29.aspx) can help, e.g.
   DWORD start, finish;
   double  duration;

   /* Measure the duration of an event. */
   start = GetTickCount();

   /* Do Something */   

   finish = GetTickCount();
   duration = (double)(finish - start) / 1000;
   printf( "%f seconds\n", duration );

Open in new window

0
 
learningunixAuthor Commented:
GetTickCount() works fine for windows Thanks.
0
 
phoffricCommented:
I was going to complete this. Shows different approaches.
//#include <sys/time.h>
//#include <windows.h>
#include <Winsock2.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>

#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
#define DELTA_EPOCH_IN_MICROSECS  11644473600000000Ui64
#else
#define DELTA_EPOCH_IN_MICROSECS  11644473600000000ULL
#endif

struct timezone
{
    int  tz_minuteswest; /* minutes W of Greenwich */
    int  tz_dsttime;     /* type of dst correction */
};
int gettimeofday(struct timeval *tv, struct timezone *tz)
{
    // http://www.suacommunity.com/dictionary/gettimeofday-entry.php
    // Define a structure to receive the current Windows filetime
    FILETIME ft;

    // Initialize the present time to 0 and the timezone to UTC
    unsigned __int64 tmpres = 0;
    static int tzflag = 0;

    if (NULL != tv)
    {
        GetSystemTimeAsFileTime(&ft);

        // The GetSystemTimeAsFileTime returns the number of 100 nanosecond
        // intervals since Jan 1, 1601 in a structure. Copy the high bits to
        // the 64 bit tmpres, shift it left by 32 then or in the low 32 bits.
        tmpres |= ft.dwHighDateTime;
        tmpres <<= 32;
        tmpres |= ft.dwLowDateTime;

        // Convert to microseconds by dividing by 10
        tmpres /= 10;

        // The Unix epoch starts on Jan 1 1970.  Need to subtract the difference
        // in seconds from Jan 1 1601.
        tmpres -= DELTA_EPOCH_IN_MICROSECS;

        // Finally change microseconds to seconds and place in the seconds value.
        // The modulus picks up the microseconds.
        tv->tv_sec = (long)(tmpres / 1000000UL);
        tv->tv_usec = (long)(tmpres % 1000000UL);
    }

    if (NULL != tz)
    {
        if (!tzflag)
        {
            _tzset();
            tzflag++;
        }

        // Adjust for the timezone west of Greenwich
        tz->tz_minuteswest = _timezone / 60;
        tz->tz_dsttime = _daylight;
    }

    return 0;
}

/* Then you can use st.wHour, st.wMinute, st.wSecond, and st.wMilliseconds
to retrieve the values (it has days, months in it too but I don't need them).*/

/* Subtract the `struct timeval' values X and Y,
storing the result in RESULT.
Return 1 if the difference is negative, otherwise 0.  */

int timeval_subtract (struct timeval *result, struct timeval *x, struct timeval *y)
{
    /* Perform the carry for the later subtraction by updating y. */
    if (x->tv_usec < y->tv_usec) {
        int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
        y->tv_usec -= 1000000 * nsec;
        y->tv_sec += nsec;
    }
    if (x->tv_usec - y->tv_usec > 1000000) {
        int nsec = (x->tv_usec - y->tv_usec) / 1000000;
        y->tv_usec += 1000000 * nsec;
        y->tv_sec -= nsec;
    }

    /* Compute the time remaining to wait.
    tv_usec is certainly positive. */
    result->tv_sec = x->tv_sec - y->tv_sec;
    result->tv_usec = x->tv_usec - y->tv_usec;

    /* Return 1 if result is negative. */
    return x->tv_sec < y->tv_sec;
}

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

    SYSTEMTIME st;
    GetSystemTime(&st);

    WORD hh = st.wHour;
    WORD mm = st.wMinute;
    WORD ss = st.wSecond;
    WORD ms = st.wMilliseconds;

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

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

    return 0;
}

Open in new window

0
 
learningunixAuthor Commented:
Thanks!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

  • 7
  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now