11

Could someone please help me to use gettimeofday() function with Visual Studio C++ 2008 on Windows XP? here is a code that I found somewhere on the net:

#include < time.h >
#include <windows.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)
{
  FILETIME ft;
  unsigned __int64 tmpres = 0;
  static int tzflag;

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

    tmpres |= ft.dwHighDateTime;
    tmpres <<= 32;
    tmpres |= ft.dwLowDateTime;

    /*converting file time to unix epoch*/
    tmpres -= DELTA_EPOCH_IN_MICROSECS; 
    tmpres /= 10;  /*convert into microseconds*/
    tv->tv_sec = (long)(tmpres / 1000000UL);
    tv->tv_usec = (long)(tmpres % 1000000UL);
  }

  if (NULL != tz)
  {
    if (!tzflag)
    {
      _tzset();
      tzflag++;
    }
    tz->tz_minuteswest = _timezone / 60;
    tz->tz_dsttime = _daylight;
  }

  return 0;
}

...
// call gettimeofday()
 gettimeofday(&tv, &tz); 
 tm = localtime(&tv.tv_sec); 

Last year when I tested this code with VC++6, it worked fine. But now as I use VC++ 2008, I am getting error of exception handling. So is there any idea on how to use gettimeofday or something equivalent?

Thanks for your reply and any help would be very appreciated:

make
  • 755
  • 7
  • 21
  • 37
  • Can you post the exception you are getting? – Jason Mar 22 '10 at 17:33
  • Please explain the actual error that you're getting--"error of exception handling" isn't very specific. – JSBձոգչ Mar 22 '10 at 17:33
  • thanks for your replies! i already posted a question regarding this error and it is on : http://stackoverflow.com/questions/2490449/how-to-solve-unhandled-exception-error-when-using-visual-c-2008 thanks again for your replies – make Mar 22 '10 at 17:59
  • Please don't post the same question multiple times. Duplicate of http://stackoverflow.com/questions/2490449/how-to-solve-unhandled-exception-error-when-using-visual-c-2008/2494647#2494647 – interjay Mar 22 '10 at 18:13
  • 1
    sorry for multiple posts. As i need a help to solve this problem, i posted different question within time of trying to solve it ... thanks again! – make Mar 22 '10 at 18:41
  • NOTE: this code is missing nullity checks around 'tv' and 'tz' arguments which will probably crashes user's program in case they send NULL in one of these arguments. See the following quote from man gettimeofday: "If either tv or tz is NULL, the corresponding structure is not set or returned. The use of the timezone structure is obsolete; the tz argument should normally be specified as NULL. " – avner Sep 16 '14 at 11:16

4 Answers4

20

In UNIX the use of the timezone struct is obsolete. I don't know why you use it. See http://linux.about.com/od/commands/l/blcmdl2_gettime.htm But if you want to use this structure to know about GMT(UTC) diffrence from your local time it will be next: tz_minuteswest is the real diffrence in minutes from GMT(UTC) and a tz_dsttime is a flag indicates whether daylight is now in use.

Your example with some changes works fine in Visual C++ 2008 Express:

#include "stdafx.h"
#include <time.h>
#include <windows.h> 

const __int64 DELTA_EPOCH_IN_MICROSECS= 11644473600000000;

/* IN UNIX the use of the timezone struct is obsolete;
 I don't know why you use it. See http://linux.about.com/od/commands/l/blcmdl2_gettime.htm
 But if you want to use this structure to know about GMT(UTC) diffrence from your local time
 it will be next: tz_minuteswest is the real diffrence in minutes from GMT(UTC) and a tz_dsttime is a flag
 indicates whether daylight is now in use
*/
struct timezone2 
{
  __int32  tz_minuteswest; /* minutes W of Greenwich */
  bool  tz_dsttime;     /* type of dst correction */
};

struct timeval2 {
__int32    tv_sec;         /* seconds */
__int32    tv_usec;        /* microseconds */
};

int gettimeofday(struct timeval2 *tv/*in*/, struct timezone2 *tz/*in*/)
{
  FILETIME ft;
  __int64 tmpres = 0;
  TIME_ZONE_INFORMATION tz_winapi;
  int rez=0;

   ZeroMemory(&ft,sizeof(ft));
   ZeroMemory(&tz_winapi,sizeof(tz_winapi));

    GetSystemTimeAsFileTime(&ft);

    tmpres = ft.dwHighDateTime;
    tmpres <<= 32;
    tmpres |= ft.dwLowDateTime;

    /*converting file time to unix epoch*/
    tmpres /= 10;  /*convert into microseconds*/
    tmpres -= DELTA_EPOCH_IN_MICROSECS; 
    tv->tv_sec = (__int32)(tmpres*0.000001);
    tv->tv_usec =(tmpres%1000000);


    //_tzset(),don't work properly, so we use GetTimeZoneInformation
    rez=GetTimeZoneInformation(&tz_winapi);
    tz->tz_dsttime=(rez==2)?true:false;
    tz->tz_minuteswest = tz_winapi.Bias + ((rez==2)?tz_winapi.DaylightBias:0);

  return 0;
}


int _tmain(int argc, _TCHAR* argv[])
{
struct timeval2 tv;
struct timezone2 tz;
struct tm *tm1; 
time_t time1;

ZeroMemory(&tv,sizeof(tv));
ZeroMemory(&tz,sizeof(tz));

gettimeofday(&tv, &tz); // call gettimeofday()
time1=tv.tv_sec;
tm1 = localtime(&time1); 



 FILE *f;
 f=fopen("rez.txt","w");

 fprintf(f,"%04d.%02d.%02d %02d:%02d:%02d\n",1900+tm1->tm_year,1+tm1->tm_mon,tm1->tm_mday,tm1->tm_hour,tm1->tm_min,tm1->tm_sec);
 fprintf(f,"Diffrence between GMT(UTC) and local time=%d %s\n",tz.tz_minuteswest,"minutes");
 fprintf(f,"Is Daylight now=%s\n",tz.tz_dsttime?"Yes":"No");

 fclose(f);
 return 0;
}
Neokoder
  • 201
  • 2
  • 4
  • This helped me alot, but I needed a more precise time. I used `GetSystemTimePreciseAsFileTime` in place of `GetSystemTimeAsFileTime`, and it worked perfectly. Cheers. – Shawn Blakesley Jun 24 '16 at 18:31
4

Simple stopwatch in seconds

FWIW: This is a similar one as that of Kate, but I just wanted to mention it, if someone is looking for the most simple stopwatch in C++ (counting seconds). Not a big deal, I know. It has only resolution of 1 sec, so if you want to cound microsecs, go on with the other examples.

double seconds=0;
time_t timer1, timer2;
time(&timer1);  /* get current time  */
...
time(&timer2);  /* get current time  later */
seconds = difftime(timer2,timer1);
Philm
  • 3,448
  • 1
  • 29
  • 28
3

There are a few different types to represent a time. Here's some code I used recently:

time_t now;
time(&now); 
tm* local = localtime(&now);

I then went on to build a string from pieces of local, but you could do what you wanted at this point.

Kate Gregory
  • 18,808
  • 8
  • 56
  • 85
  • Thanks a lot for your reply. Yes! I could use time() function but it is not as precise as gettimeofday() function and this make me a problem because I am tying to compare results I obtained on Unix with those I will obtain on Windows. thanks again! – make Mar 22 '10 at 19:04
1

In my case it worked as following: Since I wanted to find the average running time, i used: First include in the beginning of the program, then: initialize samples=100 (for example);

time_t t_start,t_end;
time(&t_start); //get the current time

//program that needs to be timed

time(&t_end); //get the time at the end of execution of the program
seconds = (difftime(t_start,t_end))/samples;//calculate the difference
Areeha
  • 823
  • 7
  • 11