我想将std::chrono::high_resolution_clock start
转换为浮点类型。我尝试使用static_cast,但是仍然出现编译错误,提示
invalid static_cast from type 'std::chrono::_V2::system_clock::time_point {aka std::chrono::time_point<std::chrono::_V2::system_clock, std::chrono::duration<long long int, std::ratio<1ll, 1000000000ll> > >}' to type 'float'
float duration = static_cast<float>(start) + static_cast<float>(ms);
和
invalid static_cast from type 'std::chrono::milliseconds {aka std::chrono::duration<long long int, std::ratio<1ll, 1000ll> >}' to type 'float'
float duration = static_cast<float>(start) + static_cast<float>(ms);
代码:
std::chrono::milliseconds ms(5000);
std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
float duration = static_cast<float>(start) + static_cast<float>(ms);
答案 0 :(得分:2)
您不能像这样投放time_point
来获得持续时间。尝试以下方法:
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
float dur_seconds = std::chrono::duration<float>(end - start).count();
如果要以秒为单位获取持续时间,则需要提供比率,例如std::milli
:
float dur_milli = std::chrono::duration<float, std::milli>(end - start).count();
std::cout << "time spent: " << dur_seconds << " seconds\n";
std::cout << "time spent: " << dur_milli << " milliseconds\n";