2012-08-07 21 views
2

我希望能夠獲得在我的C++程序中執行某些操作所需的納秒數。如何在C++中計時事件?

對象的創建,時間爲一個函數做的事情等

Java,我們會做的線沿線的東西:

long now = System.currentTimeMillis(); 
    // stuff 
    long diff = (System.currentTimeMillis() - now); 

你怎麼會做同樣的在C++?

+0

time.h http://www.cplusplus.com/reference/clibrary/ctime/ – pyCthon 2012-08-07 17:02:52

+0

我之前寫過[this](https://gist.github.com/3287323)定時器類 - 它很遠從完美,但它可能會有所幫助。 – 2012-08-07 17:08:42

回答

5

<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階段。

+0

我得到'錯誤:'std :: chrono'沒有被聲明'錯誤。請問可能會發生什麼? – JAM 2012-08-08 00:49:06

+0

@Jam您可能正在使用C++ 11之前的標準庫實現。你使用的是什麼編譯器版本和標準庫? – bames53 2012-08-08 01:08:18

+0

'i686-apple-darwin11-llvm-g ++ - 4.2(GCC)4.2.1',不知道標準庫的版本。我怎樣才能找到它? – JAM 2012-08-08 14:04:53

0
+0

不幸的是,沒有人給出正確答案,''。 – bames53 2012-08-07 18:45:03

+0

你是什麼意思「正確答案」?這是一個C++ 11的特性,OP沒有提到支持。 – 2012-08-07 18:46:52

+0

Chrono是標準配置,爲時間點vs.時間點提供類型安全性持續時間和單位,並且不會因爲更高的分辨率變得可用而需要新的API,所以在大多數情況下,我認爲使用clock_gettime(),clock(),gettimeofday(),QueryPerformanceFrequency()等是一個錯誤。 – bames53 2012-08-07 18:58:25

1

看看clockclock_t。對於你正在談論的解決方案,我不認爲在C++中有本地支持。爲了獲得有意義的值,您必須定時調用多個調用或構造,或者使用探查器(所需)。

0

今天早些時候我問了這個確切的問題。目前最好的解決辦法我是使用SDL,並呼籲:

uint32 a_time = SDL_GetTicks(); // Return uint32 count of milliseconds since SDL_Init was called 

儘管這可能會給你大量的開銷,即使你只是初始化SDL與定時器功能。 (SDL_Init(SDL_INIT_TIMER)

希望這可以幫助你 - 我解決這個作爲一個解決方案,因爲它是便攜式

2

在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

+0

''在VS2012 RC中,但我認爲high_resolution_clock的tick只有100ns。它應該在其他平臺上更好。 OS X上的libC++具有ns分辨率。我不確定gcc或libstdC++。 – bames53 2012-08-07 18:43:15