我希望能夠獲得在我的C++程序中執行某些操作所需的納秒數。如何在C++中計時事件?
對象的創建,時間爲一個函數做的事情等
在Java
,我們會做的線沿線的東西:
long now = System.currentTimeMillis();
// stuff
long diff = (System.currentTimeMillis() - now);
你怎麼會做同樣的在C++?
我希望能夠獲得在我的C++程序中執行某些操作所需的納秒數。如何在C++中計時事件?
對象的創建,時間爲一個函數做的事情等
在Java
,我們會做的線沿線的東西:
long now = System.currentTimeMillis();
// stuff
long diff = (System.currentTimeMillis() - now);
你怎麼會做同樣的在C++?
的<chrono>
庫標準C++提供做到這一點的最好辦法。這個庫提供了一個標準,類型安全的時鐘通用API。
#include <chrono>
#include <iostream>
int main() {
using std::chrono::duration_cast;
using std::chrono::nanoseconds;
typedef std::chrono::high_resolution_clock clock;
auto start = clock::now();
// stuff
auto end = clock::now();
std::cout << duration_cast<nanoseconds>(end-start).count() << "ns\n";
}
時鐘的實際分辨率將實現之間有所不同,但是這個代碼將始終顯示結果納秒,儘可能準確地給出實施的Tick階段。
看看clock
和clock_t
。對於你正在談論的解決方案,我不認爲在C++中有本地支持。爲了獲得有意義的值,您必須定時調用多個調用或構造,或者使用探查器(所需)。
今天早些時候我問了這個確切的問題。目前最好的解決辦法我是使用SDL,並呼籲:
uint32 a_time = SDL_GetTicks(); // Return uint32 count of milliseconds since SDL_Init was called
儘管這可能會給你大量的開銷,即使你只是初始化SDL與定時器功能。 (SDL_Init(SDL_INIT_TIMER)
希望這可以幫助你 - 我解決這個作爲一個解決方案,因爲它是便攜式
在C++ 11可以使用計時圖書館,在那裏做 -
Class template std::chrono::duration represents a time interval. It consists of a count of ticks of type Rep and a tick period, where the tick period is a compile-time rational constant representing the number of seconds from one tick to the next.
在GCC 4.5.1目前正在執行(尚未在VC++)。在Ideone.com execution time of a function call見示例代碼cppreference.com
'
time.h http://www.cplusplus.com/reference/clibrary/ctime/ – pyCthon 2012-08-07 17:02:52
我之前寫過[this](https://gist.github.com/3287323)定時器類 - 它很遠從完美,但它可能會有所幫助。 – 2012-08-07 17:08:42