2015-01-15 48 views
0

無論我嘗試什麼,我都無法得到一個簡單的計時器。如何查看一段代碼在沒有外部庫的情況下運行需要多少毫秒?定時功能

我曾嘗試:

time_t total = static_cast<time_t>(0.0f); 
for(int i = 0; i < 10; ++i) 
{ 
    time_t start = time(0); 
    for(int b = 0; b < 100; ++b) 
    { 
     newMesh.IsValid(); 
    } 
    time_t end = time(0); 
    total += (end - start); 
} 

time_t average = total/10; 
printf("Average time of Knight IsValid check %d\n", average); 

這大約需要15秒,說花了1毫秒。我也嘗試過:

std::clock_t total = static_cast<time_t>(0.0f); 
for(int i = 0; i < 10; ++i) 
{ 
    std::clock_t start = std::clock(); 
    for(int b = 0; b < 100; ++b) 
    { 
     newMesh.IsValid(); 
    } 
    std::clock_t end = std::clock(); 
    total += (end - start); 
} 

std::clock_t average = total/10; 
printf("Average time of Knight IsValid check %d\n", average); 

但我被告知那是時鐘滴答,不適合剖析?

+1

上有[cppreference.com](http://en.cppreference.com/w/cpp/chrono/steady_clock/now),我一個非常簡單的例子認爲會做你需要的。 – 5gon12eder

+0

似乎沒有chrono?我正在使用Visual Studio 2012. – marsh

+0

這是一個C++ 11功能。也許你需要爲GCC添加一個特殊的編譯器標誌,比如'-std = C++ 11'或者升級你的編譯器。這將是值得的事情。 – 5gon12eder

回答

0

在C++ 11可以使用<chrono>(海合會4.9.1正與C++ 11和Visual Studio 2012更新2):

示例代碼:

#include <iostream> 
#include <chrono> 
#include <iomanip> 

int main() { 
    std::chrono::steady_clock::time_point begin_time = std::chrono::steady_clock::now(); 

    // add code to time here 

    std::chrono::steady_clock::time_point end_time = std::chrono::steady_clock::now(); 
    long long elapsed_seconds = std::chrono::duration_cast<std::chrono::seconds>(end_time - begin_time).count(); 
    std::cout << "Duration (min:seg): " << std::setw(2) << std::setfill('0') << (elapsed_seconds/60) << ":" << std::setw(2) << std::setfill('0') << (elapsed_seconds % 60) << std::endl; 

    return 0; 
} 

你可以實例duration_cast與其他時間測量(如毫秒,納秒等)。與示例代碼
更多信息底:http://en.cppreference.com/w/cpp/chrono

+0

'std :: system_clock'可能不是性能計時的最佳選擇,因爲它的時間概念受到隨機調整(例如通過NTP守護進程)的影響。更好地使用'std :: steady_clock'。 – 5gon12eder

+0

不幸的是我無法訪問chrono。 – marsh

+0

在你說的使用VS2012的評論中,這已經在VS2012 Update2中測試過了,確定你沒有計時器,或者沒有使用過的簡單的其他原因。 – NetVipeC