2010-03-22 11 views
10

¿Podría alguien ayudarme a utilizar la función gettimeofday() con Visual Studio C++ 2008 en Windows XP? aquí es un código que he encontrado en algún lugar de la red:cómo usar gettimeofday() o algo equivalente con Visual Studio C++ 2008?

#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); 

año pasado cuando probé este código con VC++ 6, que funcionaba bien. Pero ahora, cuando uso VC++ 2008, recibo un error de manejo de excepciones. Entonces, ¿hay alguna idea sobre cómo usar gettimeofday o algo equivalente?

Gracias por su respuesta y de cualquier ayuda sería muy apreciada:

+0

¿Puede publicar la excepción que está recibiendo? – Jason

+0

Explique el error real que está recibiendo: "error de manejo de excepciones" no es muy específico. –

+0

gracias por sus respuestas! Ya he publicado una pregunta sobre este error y está en: http://stackoverflow.com/questions/2490449/how-to-solve-unhandled-exception-error-when-using-visual-c-2008 gracias de nuevo por sus respuestas – make

Respuesta

2

Hay unos pocos tipos diferentes para representar a la vez. Aquí hay un código Recientemente he usado:

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

Entonces fui para construir una cadena de piezas de local, pero se podía hacer lo que quería en este punto.

Kate

+0

Gracias a mucho para su respuesta. ¡Sí! Podría usar la función time() pero no es tan precisa como la función gettimeofday() y esto me convierte en un problema porque estoy tratando de comparar los resultados que obtuve en Unix con los que obtendré en Windows. ¡gracias de nuevo! – make

18

En UNIX el uso de la estructura zona horaria es obsoleto. No sé por qué lo usas. Consulte http://linux.about.com/od/commands/l/blcmdl2_gettime.htm Pero si desea utilizar esta estructura para conocer la diferencia GMT (UTC) de su hora local, será la siguiente: tz_minuteswest es la diferencia real en minutos de GMT (UTC) y tz_dsttime es una bandera que indica si la luz del día es ahora en uso.

Su ejemplo, con algunos cambios funciona bien en 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; 
} 
+0

Esto me ayudó mucho, pero necesitaba un tiempo más preciso.Usé 'GetSystemTimePreciseAsFileTime' en lugar de' GetSystemTimeAsFileTime', y funcionó perfectamente. Aclamaciones. –

3

simple cronómetro en segundos

Fwiw: Esta es una similar a la de Kate, pero yo sólo quería para mencionarlo, si alguien está buscando el cronómetro más simple en C++ (contando segundos). No es un gran problema, lo sé. Solo tiene una resolución de 1 segundo, por lo que si desea utilizar microsecs, continúe con los otros ejemplos.

double seconds=0; 
time_t timer1, timer2; 
time(&timer1); /* get current time */ 
... 
time(&timer2); /* get current time later */ 
seconds = difftime(timer2,timer1); 
Cuestiones relacionadas