Solved

time diff

Posted on 2010-09-21
13
514 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
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

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

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
best sources to up-to-date in C++? 8 91
show out valin of json for debugging in visaul c++ 1 41
Outlook 13 45
learn programming 8 42
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

828 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