c++coutc++-chrono

Timing a function in C++ using chrono and printing result


I am trying to time a function in C++. To this extent I have tested the following code

#include <chrono>
#include <iostream>

int main()
{
    auto t = std::chrono::high_resolution_clock::now();
    std::cout << t.time_since_epoch() << '\n';
}

I attempt to compile this in my console by

clang++ -std=c++20 -stdlib=libc++ test3.cpp -o test5

as my C++-file name is test3.cpp. However, it gives me a long list of errors when it tries to compile the code:

test3.cpp:7:15: error: invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'std::chrono::time_point<std::chrono::steady_clock, std::chrono::duration<long long, std::ratio<1, 1000000000>>>::duration' (aka 'std::chrono::duration<long long, std::ratio<1, 1000000000>>'))
    std::cout << t.time_since_epoch() << '\n';
    ~~~~~~~~~ ^  ~~~~~~~~~~~~~~~~~~~~
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/cstddef:116:3: note: candidate function template not viable: no known conversion from 'std::ostream' (aka 'basic_ostream<char>') to 'std::byte' for 1st argument
  operator<< (byte  __lhs, _Integer __shift) noexcept

It works completely fine when I replace the t.time_since_epoch() by a string. Also, if I define a variable in the script with t.time_since_epoch(), i.e.

#include <chrono>
#include <iostream>

int main()
{
    auto t = std::chrono::high_resolution_clock::now();
    auto t2 = t.time_since_epoch();
    std::cout << "test" << '\n';
}

This gets compiled with no errors. So it seems that the t.time_since_epoch() works, but my cout-function does not know how to print it. Any ideas on how to fix this? According to this post: std::chrono and cout the code should be working.


Solution

  • Your code is legal C++20. Unfortunately libc++ has not yet implemented this part of C++20.

    You can use my free, open-source, header-only C++20 chrono preview library as a workaround until your vendor fully implements C++20:

    #include "date/date.h"  // add this
    #include <chrono>
    #include <iostream>
    
    int main()
    {
        using date::operator<<;  // add this
        auto t = std::chrono::high_resolution_clock::now();
        std::cout << t.time_since_epoch() << '\n';
    }
    

    Example output:

    1666477458303541ns