Search code examples
c++functionautoc++-chrono

No instance of constructor when trying to make a function for chrono in C++


I need to calculate the runtime of my algorithms. I am using the following structure to do this:

auto start = std::chrono::stedy_clock::now();
//code
auto end = std::chrono::stedy_clock::now();
auto diff = end - start;
std::cout << std::chrono::duration <double, std::milli> (diff).count() << " ms" << endl;

However, since I have multiple algorithms I need to test I decided to make the following functions:

std::chrono::time_point<std::chrono::steady_clock> time_now()
{
    return std::chrono::steady_clock::now();
}

void print_time(std::ostream& out, std::chrono::_V2::steady_clock differnce)
{
    out << std::chrono::duration <double, std::micro> (differnce).count() << std::endl;
}

I get the following error from vscode for my print function:

no instance of constructor "std::chrono::duration<_Rep, _Period>::duration [with _Rep=double, _Period=std::micro]" matches the argument list -- argument types are: (std::chrono::_V2::steady_clock)

Any idea why I have this problem and how I can solve it?

Thank you!


Solution

  • You're passing the wrong type to your print_time function. The function is being declared, but when you pass your duration into it, the compiler is trying to convert a duration into a clock which doesn't make sense, which is why you're getting that constructor message.

    Some of the time types are:

    • clock(s) various things we can query for specific time_points with now()
    • time_points represents a specific instant in time.
    • duration a difference between time_points

    It should be this:

    void print_time(std::ostream& out,
      std::chrono::duration<double, std::micro> delta)
    {
        out << delta.count() << std::endl;
    }