Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

time diff

Posted on 2010-09-21
13
Medium Priority
?
530 Views
Last Modified: 2012-05-10
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
Comment
Question by:learningunix
  • 7
  • 4
  • 2
13 Comments
 
LVL 33

Expert Comment

by:phoffric
ID: 33728864
difftime: "Calculates the difference in seconds between time1 and time2."
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 33

Expert Comment

by:phoffric
ID: 33728879
You can consider using gettimeofday() which uses struct timeval     http://www.opengroup.org/onlinepubs/000095399/functions/gettimeofday.html
0
 
LVL 33

Expert Comment

by:phoffric
ID: 33728896
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
 
LVL 86

Expert Comment

by:jkr
ID: 33728941
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
 
LVL 33

Expert Comment

by:phoffric
ID: 33730421
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
 

Author Comment

by:learningunix
ID: 33733834
I keep getting cannot open include files <sys/time.h> on my windows platform
0
 
LVL 33

Expert Comment

by:phoffric
ID: 33734051
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
 
LVL 86

Accepted Solution

by:
jkr earned 1200 total points
ID: 33734831
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
 

Author Comment

by:learningunix
ID: 33736185
GetTickCount() works fine for windows Thanks.
0
 
LVL 33

Assisted Solution

by:phoffric
phoffric earned 800 total points
ID: 33736194
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
 

Author Closing Comment

by:learningunix
ID: 33743581
Thanks!
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.
Suggested Courses

581 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question