gpt4 book ai didi

C++计时: Get seconds with a precision of 3 decimal places

转载 作者:搜寻专家 更新时间:2023-10-31 01:33:49 26 4
gpt4 key购买 nike

这听起来像是一个基本问题,但我已经搜索了很多。我正在尝试对 C++ 中的函数调用进行时间剖析,并且需要以秒为单位记录时间,最多 3 位小数。例如 2.304 秒.791 秒。我正在尝试使用 std::chrono 这样做:

auto start_time = std::chrono::system_clock::now();
DoSomeOperation();
std::chrono::duration<double> elapsed_time = std::chrono::system_clock::now() - start_time;
double execution_time = elapsed_time.count();

std::cout << "execution_time = " << execution_time << std::endl;

以下是我得到的输出:

execution_time = 1.9e-05
execution_time = 2.1e-05
execution_time = 1.8e-05
execution_time = 1.7e-05

我确信 DoSomeOperation 只需几 毫秒 即可完成,我需要 内的数字。我需要 double 中的数字才能在不同的计算中使用它。

我怎样才能将这个奇怪的 1.9e-05 转换成 double 中的合理数字,它在几秒钟内产生 .304.067

尝试来自 here 的代码,我有同样的问题。

最佳答案

要更改输出格式,请尝试 std::fixedstd::setprecision

double execution_time = 0.01234;
std::cout << "execution_time = "
<< std::fixed << std::setprecision(3)
<< execution_time << std::endl;

如果有几个地方需要输出执行时间,可以转成字符串再使用:

double execution_time = 0.01234;
std::stringstream stream;
stream << std::fixed << std::setprecision(3) << execution_time;
std::string execution_time_as_string = stream.str();

std::cout << "execution_time = " << execution_time_as_string << std::endl;

关于C++计时: Get seconds with a precision of 3 decimal places,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40705817/

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