2010-05-14 15 views
6

En Java se puede hacer esto:cómo obtener la hora en Millis en C++ como Java

long now = (new Date()).getTime(); 

¿Cómo puedo hacer lo mismo pero en C++?

+0

Compruebe este hilo (son nanosegundos, pero creo que podría convertirse en milisegundos también) http://stackoverflow.com/questions/275004/c-timer-function-to-provide-time-in- nano-segundos – Default

+5

En Java debe usar 'System.currentTimeMillis()'. –

Respuesta

9

No existe tal método en C++ estándar (en C++ estándar, solo hay segunda precisión, no milisegundos). Puede hacerlo de forma no portátil, pero como no especificó, asumiré que desea una solución portátil. Su mejor opción, diría yo, es la función de refuerzo microsec_clock::local_time().

+1

+1: 'boost :: datetime' es realmente genial. – ereOn

5

Me gustaría tener una función llamada time_ms definido como tal:

// Used to measure intervals and absolute times 
typedef int64_t msec_t; 

// Get current time in milliseconds from the Epoch (Unix) 
// or the time the system started (Windows). 
msec_t time_ms(void); 

La ejecución cuáles debería funcionar en Windows, así como los sistemas de tipo Unix.

#if defined(__WIN32__) 

#include <windows.h> 

msec_t time_ms(void) 
{ 
    return timeGetTime(); 
} 

#else 

#include <sys/time.h> 

msec_t time_ms(void) 
{ 
    struct timeval tv; 
    gettimeofday(&tv, NULL); 
    return (msec_t)tv.tv_sec * 1000 + tv.tv_usec/1000; 
} 

#endif 

Tenga en cuenta que la hora devuelta por la rama de Windows es milisegundos desde que se inició el sistema, mientras que la hora devuelta por la rama de Unix es milisegundos desde 1970. Por lo tanto, si se utiliza este código, sólo se basan en las diferencias entre los tiempos , no el tiempo absoluto en sí mismo.

+1

timeGetTime devuelve el tiempo desde que se inició Windows, no los milisegundos desde la Época. –

+1

Puede usar un poco de matemática y 'GetSystemTimeAsFileTime' en Windows (http://msdn.microsoft.com/en-us/library/ms724397%28v=VS.85%29.aspx).Personalmente, me gusta 'microsec_clock :: local_time()' - todo el trabajo duro ya se ha hecho :-) –

+0

¿Se puede cambiar el comentario sobre el prototipo 'time_ms' también? –

9

Debido a que C++ 0x es impresionante

namespace sc = std::chrono; 

auto time = sc::system_clock::now(); // get the current time 

auto since_epoch = time.time_since_epoch(); // get the duration since epoch 

// I don't know what system_clock returns 
// I think it's uint64_t nanoseconds since epoch 
// Either way this duration_cast will do the right thing 
auto millis = sc::duration_cast<sc::milliseconds>(since_epoch); 

long now = millis.count(); // just like java (new Date()).getTime(); 

This works con gcc 4.4+. Compilarlo con --std=c++0x. No sé si VS2010 implementa std::chrono todavía.

+0

duration_cast abre una plantilla dos veces, pero la cierra una vez ... – VDVLeon

+0

gracias, lo arregló. –

+0

Su duration_cast debe ser: "auto millis = sc :: duration_cast (since_epoch);" –

2

Puede probar este código (obtener de STOCKFISH código fuente del motor de ajedrez (GPL)):

#include <iostream> 
#include <stdio> 

#if !defined(_WIN32) && !defined(_WIN64) // Linux - Unix 
    # include <sys/time.h> 
    typedef timeval sys_time_t; 
    inline void system_time(sys_time_t* t) { 
     gettimeofday(t, NULL); 
    } 
    inline long long time_to_msec(const sys_time_t& t) { 
     return t.tv_sec * 1000LL + t.tv_usec/1000; 
    } 
    #else // Windows and MinGW 
    # include <sys/timeb.h> 
    typedef _timeb sys_time_t; 
    inline void system_time(sys_time_t* t) { _ftime(t); } 
    inline long long time_to_msec(const sys_time_t& t) { 
     return t.time * 1000LL + t.millitm; 
    } 
#endif 


int main() { 
    sys_time_t t; 
    system_time(&t); 
    long long currentTimeMs = time_to_msec(t); 
    std::cout << "currentTimeMs:" << currentTimeMs << std::endl; 
    getchar(); // wait for keyboard input 
} 
Cuestiones relacionadas