2012-11-27 38 views
4

所以我试图使用std :: chrono :: high_resolution_clock来计算执行时间需要多长时间。我计算过,你可以找到的开始时间和结束时间之间的区别...std :: chrono :: high_resolution_clock中的不准确性?

要检查我的做法的作品,我做了以下程序:

#include <iostream> 
#include <chrono> 
#include <vector> 

void long_function(); 

int main() 
{ 
    std::chrono::high_resolution_clock timer; 
    auto start_time = timer.now(); 

    long_function(); 

    auto end_time = timer.now(); 
    auto diff_millis = std::chrono::duration_cast<std::chrono::duration<int, std::milli>>(end_time - start_time); 

    std::cout << "It took " << diff_millis.count() << "ms" << std::endl; 
    return 0; 
} 

void long_function() 
{ 
    //Should take a while to execute. 
    //This is calculating the first 100 million 
    //fib numbers and storing them in a vector. 
    //Well, it doesn't actually, because it 
    //overflows very quickly, but the point is it 
    //should take a few seconds to execute. 
    std::vector<unsigned long> numbers; 
    numbers.push_back(1); 
    numbers.push_back(1); 
    for(int i = 2; i < 100000000; i++) 
    { 
     numbers.push_back(numbers[i-2] + numbers[i-1]); 
    } 
} 

的问题是,它只是输出3000ms确切地说,当它显然不是那个时候。

在较短的问题,它只输出0毫秒......我做错了什么?

编辑:如果它有什么用途,我使用的GNU GCC编译器-std = C++ 0x中旗

+0

在我的窗口框中,它报告使用MSVC 17.00.50727.1(VSExpress2012)和GCC 4.8.0 20120924 – sehe

+4

的准确时间Nitpick:更喜欢'typedef std :: chrono :: high_resolution_clock timer; auto start_time = timer :: now();'as now()是静态成员 – sehe

+0

我没有看到代码有什么问题,对于更短的时间,你可能只需要将句号改为'std :: nano',等等。 –

回答

2

的high_resolution_clock的分辨率取决于平台。

打印下面会给你下一个window7的执行决议的想法您使用

std::cout << "It took " << std::chrono::nanoseconds(end_time - start_time).count() << std::endl; 
1

我有相克类似的问题++(rev5,由MinGW的-W64内置项目)4.8.1 。

int main() 
{ 
    auto start_time = std::chrono::high_resolution_clock::now(); 
    int temp(1); 
    const int n(1e7); 
    for (int i = 0; i < n; i++) 
     temp += temp; 
    auto end_time = std::chrono::high_resolution_clock::now(); 
    std::cout << std::chrono::duration_cast<std::chrono::nanoseconds>(end_time - start_time).count() << " ns."; 
    return 0; 
} 

如果n = 1E7它显示19999800纳秒 但如果 N = 1E6显示为0毫微秒。

精度似乎很弱。

+0

你也应该把'temp'变量发送到std :: cout,否则,编译器可能会把它和整个循环一起消除,巧妙地看到你没有做任何事情。 –

+0

也许mingw的高分辨率时钟在该版本上并不是真正的高分辨率。它看起来像1毫秒或2毫秒(n = 1e6)的数量可能最终为零。也许重复这个措施会显示出“爆发”,例如在10或15ms时,表示低分辨率约10-15ms(用linux的说法,窗口的默认“HZ”值) –

相关问题