Search code examples
c++timec++-chronohigh-resolution-clock

error: 'high_resolution_clock' has not been declared


I am using g++ version 8.1.0 on windows 10 but still when I try to compile

auto start=high_resolution_clock::now();
rd(n);
auto stop=high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop-start);
cout<<duration.count()<<endl;

I get the error as

error: 'high_resolution_clock' has not been declared
 auto start=high_resolution_clock::now();
            ^~~~~~~~~~~~~~~~~~~~~

I have included both chrono and time.h


Solution

  • You need to specify the std::chrono:: namespace qualifier in front of high_resolution_clock, microseconds, and duration_cast, eg:

    #include <chrono>
    
    auto start = std::chrono::high_resolution_clock::now();
    rd(n);
    auto stop = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop-start);
    std::cout << duration.count() << std::endl;
    

    Otherwise, you can use using statements instead, eg:

    #include <chrono>
    using namespace std::chrono;
    
    auto start = high_resolution_clock::now();
    rd(n);
    auto stop = high_resolution_clock::now();
    auto duration = duration_cast<microseconds>(stop-start);
    std::cout << duration.count() << std::endl;
    

    or:

    #include <chrono>
    using std::chrono::high_resolution_clock;
    using std::chrono::microseconds;
    using std::chrono::duration_cast;
    
    auto start = high_resolution_clock::now();
    rd(n);
    auto stop = high_resolution_clock::now();
    auto duration = duration_cast<microseconds>(stop-start);
    std::cout << duration.count() << std::endl;