2012-06-05 20 views
17

¿Alguien conoce una función equivalente de la función gettimeofday() en el entorno de Windows? Estoy comparando un tiempo de ejecución de código en Linux vs Windows. Estoy usando MS Visual Studio 2010 y sigue diciendo que el identificador "gettimeofday" no está definido.Equivalente a gettimeday() para Windows

Agradecido por cualquier apuntador.

+2

posible duplicado de (http://stackoverflow.com/questions/1676036/what-should- i-use-to-replace-gettimeofday-on-windows) –

Respuesta

8

GetLocalTime() durante el tiempo en el sistema zona horaria, GetSystemTime() para UTC. Si desea un tiempo de segundos desde la época, use SystemTimeToFileTime() o GetSystemTimeAsFileTime().

Para tomar un intervalo, use GetTickCount(). Devuelve milisegundos desde el inicio.

Para tomar intervalos con la mejor resolución posible (limitado solo por hardware), use QueryPerformanceCounter().

54

Aquí es una implementación libre: [? ¿Qué debo usar para reemplazar gettimeofday() en Windows]

#define WIN32_LEAN_AND_MEAN 
#include <Windows.h> 
#include <stdint.h> // portable: uint64_t MSVC: __int64 

// MSVC defines this in winsock2.h!? 
typedef struct timeval { 
    long tv_sec; 
    long tv_usec; 
} timeval; 

int gettimeofday(struct timeval * tp, struct timezone * tzp) 
{ 
    // Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's 
    // This magic number is the number of 100 nanosecond intervals since January 1, 1601 (UTC) 
    // until 00:00:00 January 1, 1970 
    static const uint64_t EPOCH = ((uint64_t) 116444736000000000ULL); 

    SYSTEMTIME system_time; 
    FILETIME file_time; 
    uint64_t time; 

    GetSystemTime(&system_time); 
    SystemTimeToFileTime(&system_time, &file_time); 
    time = ((uint64_t)file_time.dwLowDateTime)  ; 
    time += ((uint64_t)file_time.dwHighDateTime) << 32; 

    tp->tv_sec = (long) ((time - EPOCH)/10000000L); 
    tp->tv_usec = (long) (system_time.wMilliseconds * 1000); 
    return 0; 
} 
+0

Gracias :) :) :) – Omeriko

+0

Muy bien. Tengo un código que se incluyó en esta implementación. Exactamente el mismo, pero necesito tener este código trabajando en Linux y no sé cómo hacerlo. ¿Cómo implementaría esta pieza de código para compilar en Linux usando esta misma implementación usando C++ o C? Thks – S4nD3r

+0

@ S4nD3r #ifdef _WIN32 ... incluye líneas arriba ... #else #include #endif ... Ver mi uso en mi proyecto de Buddhabrot: https://raw.githubusercontent.com/Michaelangel007/buddhabrot/master /buddhabrot.cpp – Michaelangel007