gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:21:20 27 4
gpt4 key购买 nike

我想将 std::chrono::high_resolution_clock start 转换为 float 类型。我尝试使用 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);

最佳答案

您不能像这样转换 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";

关于c++ - 如何将 std::chrono::high_resolution 类型转换为 float 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56138064/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com