Inaccuracy in std::chrono::high_resolution_clock? [duplicate]

六月ゝ 毕业季﹏ 提交于 2019-12-07 06:30:31

问题


So I was trying to use std::chrono::high_resolution_clock to time how long something takes to executes. I figured that you can just find the difference between the start time and end time...

To check my approach works, I made the following program:

#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]);
    }
}

The problem is, it just outputs 3000ms exactly, when it clearly wasn't actually that.

On shorter problems, it just outputs 0ms... What am I doing wrong?

EDIT: If it's of any use, I'm using the GNU GCC compiler with -std=c++0x flag on


回答1:


The resolution of the high_resolution_clock depends on the platform.

Printing the following will give you an idea of the resolution of the implementation you use

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



回答2:


I have got a similar problem with g++ (rev5, Built by MinGW-W64 project) 4.8.1 under window7.

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;
}

if n=1e7 it displays 19999800 ns but if n=1e6 it displays 0 ns.

the precision seems weak.



来源:https://stackoverflow.com/questions/13595062/inaccuracy-in-stdchronohigh-resolution-clock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!