error: 'high_resolution_clock' has not been declared

error: 'high_resolution_clock' has not been declared

我在 windows 10 上使用 g++ 8.1.0 版,但当我尝试编译时仍然如此

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;

我得到的错误是

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

我已经包含了 chrono 和 time.h

需要在high_resolution_clockmicrosecondsduration_cast前指定std::chrono::命名空间限定符,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;

否则,您可以使用using语句代替,例如:

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

或:

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

哦,我刚找到解决方案, 我忘了使用 chrono 命名空间 所以代码应该是:

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