Solved

time diff

Posted on 2010-09-21
13
511 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Writing a parser for java language 4 71
How to convert MFC::CString to UTF8 wchar_t* 10 137
Add values of each row in an array 3 50
Super Scope, DHCP 5 50
An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…

932 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

9 Experts available now in Live!

Get 1:1 Help Now