2013-05-09 146 views
0

我想獲得系統的毫秒時間(我不在乎它是否是實時,我希望它儘可能準確)。這是一個很好的方法嗎?Linux和Windows毫秒時間

#ifdef WIN32 
unsigned long long freq; 
unsigned long long get_ms_time() { 
    LARGE_INTEGER t; 
    QueryPerformanceCounter(&t); 
    return t.QuadPart/freq; 
} 
#else 
unsigned long long get_ms_time() { 
    struct timespec t; 
    clock_gettime(CLOCK_MONOTONIC, &t); 
    return t.tv_sec * 1000 + t.tv_nsec/1000000; 
} 
#endif 

如何將此值包裹到signed int?我嘗試這樣做,並得到像這樣的負值(在Linux上,我不知道在Windows上):

~ start 
-2083002438 
~ 15 seconds after.. 
-2082987440 
~ 15 seconds after.. 
-2082972441 

我會這樣。 〜開始 X 〜15秒後.. X + 14998 〜15秒後.. X + 29997

當X是一個正數。 (我想輸出正和增加)

+0

你爲什麼不告訴我們你的代碼? – Nick 2013-05-09 11:30:18

+0

你顯示的代碼看起來不錯,所以我懷疑你打印的是錯誤的值+或者做了其他錯誤。 – 2013-05-09 11:37:28

+0

int x =(int)get_ms_time(); cout << x; – dan 2013-05-09 11:37:45

回答

0

我做這樣的事情在我的代碼...

timespec specStart, specStop; 

// Get start time (UNIX timestamp) in seconds... 
clock_gettime(CLOCK_MONOTONIC_RAW, &startTime); 

int startTimeInt = startTime.tv_sec; 
std::cout << "start time : " << startTimeInt << std::endl; 

... 
// Get stop time (UNIX timestamp) in seconds... 
clock_gettime(CLOCK_MONOTONIC_RAW, &stopTime); 

int stopTimeInt = stopTime.tv_sec; 
std::cout << "stop time : " << stopTimeInt << std::endl; 

// Get time diff from stop time to start time 
unsigned long long timeStart = specStart.tv_sec * 1000000000 + specStart.tv_nsec; 
unsigned long long timeStop = specStop.tv_sec * 1000000000 + specStop.tv_nsec; 
unsigned long long timeDelta = timeStio - timeStart; // Time diff in nanoseconds. 

int microSec = timeDelate/1000; 
int mSec = timeDelta/1000000; 
int sec = timeDelta/1000000000; 

std::cout << "time diff : " << std::endl 
    << sec << " s" << std::endl 
    << msec << " ms" << std::endl 
    << microSec << " µs" << std::endl 
    << timeDelta << " ns" << std::endl;