Solved

time diff

Posted on 2010-09-21
13
509 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
 

Author Comment

by:learningunix
ID: 33728817
0
 
LVL 32

Expert Comment

by:phoffric
ID: 33728854
0
 
LVL 32

Expert Comment

by:phoffric
ID: 33728864
difftime: "Calculates the difference in seconds between time1 and time2."
0
 
LVL 32

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 32

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
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 32

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 32

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 300 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 32

Assisted Solution

by:phoffric
phoffric earned 200 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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.

746 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now