2015-01-15 37 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