如何将std :: chrono :: high_resolution类型转换为float类型?

时间:2019-05-14 20:22:13

标签: c++

我想将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);

1 个答案:

答案 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";