2012-10-19 19 views
4

我有以下代碼:使用boost :: posix_time :: microsec_clock進行測量的錯誤超過10微秒?

long long unsigned int GetCurrentTimestamp() 
{ 
    LARGE_INTEGER res; 
    QueryPerformanceCounter(&res); 
    return res.QuadPart; 
} 


long long unsigned int initalizeFrequency() 
{ 
    LARGE_INTEGER res; 
    QueryPerformanceFrequency(&res); 
    return res.QuadPart; 
} 


//start time stamp 
boost::posix_time::ptime startTime = boost::posix_time::microsec_clock::local_time(); 
long long unsigned int start = GetCurrentTimestamp(); 


// .... 
// execution that should be measured 
// .... 

long long unsigned int end = GetCurrentTimestamp(); 
boost::posix_time::ptime endTime = boost::posix_time::microsec_clock::local_time(); 
boost::posix_time::time_duration duration = endTime - startTime; 
std::cout << "Duration by Boost posix: " << duration.total_microseconds() <<std::endl; 
std::cout << "Processing time is " << ((end - start) * 1000000/initalizeFrequency()) 
      << " microsec "<< std::endl; 

這段代碼的結果是

Duration by Boost posix: 0 
Processing time is 24 microsec 

爲什麼有這麼大的差異? Boost吸收儘可​​能多,因爲它應該測量微秒,但它會測量微秒的十微秒誤差?

回答

4

POSIX時間:microsec_clock:

使用子第二分辨率時鐘獲取UTC時間。在Unix系統上,這是使用GetTimeOfDay實現的。在大多數Win32平臺上,它使用ftime來實現。通過這個API,Win32系統通常不會達到微秒級的分辨率。如果更高的分辨率對您的應用至關重要,請測試您的平臺以查看實現的分辨率

ftime根本不提供微秒的分辨率。該參數可能包含單詞microsecond,但該實現不提供該範圍內的任何準確性。它的粒度處於ms狀態。

當您的手術需要更多時間,比如至少20ms時,您會得到與ZERO不同的東西。

編輯:注:從長期來看,microsec_clock執行的Windows 應該使用GetSystemTimePreciseAsFileTime function可能時(最少REQ Windows 8桌面,Windows Server 2012中的桌面)來實現微秒級的分辨率。的boost::posix_time::microsec_clock

+0

這只是意味着boost :: posix_time :: microsec_clock是一個謊言:)) – Narek

+0

你不能說這是一個謊言。讓值攜帶微秒是有意義的,因爲這些值確實攜帶了微秒範圍內的信息。但粒度不在該範圍內。一個典型的情況是時鐘和速度乘以156,250 100納秒。這是15.625毫秒,換句話說是15毫秒和625微秒。 **但時鐘有這麼多。它具有這樣的粒度。** – Arno

相關問題