You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让C++ std::chrono输出毫秒、纳秒或秒?

如何用std::chrono输出毫秒/纳秒/秒级计时结果?

问题背景

现有一段基于std::chrono::steady_clock的C++计时代码,原代码默认输出秒级浮点数结果(如7.708e-06),想要改为输出毫秒、纳秒或明确的秒格式,但修改时触发编译错误。

原代码

#include <iostream>
#include <chrono>
#include <cstring>  // 补充原代码缺失的strlen依赖头文件

using namespace std;

class Time
{
    chrono::steady_clock::time_point start;

public:
    Time()
    {
        start = chrono::steady_clock::now();
    }

    ~Time()
    {
        auto end = chrono::steady_clock::now();
        std::chrono::duration<double> time = end-start;

        cout << "time " << time.count() << endl;
    }
};

void revstr(char* input)
{
    int length = strlen(input);
    int last_pos = length-1;
    for(int i = 0; i < length/2; i++)
    {
        char tmp = input[i];
        input[i] = input[last_pos - i];
        input[last_pos - i] = tmp;
    }
}

int main()
{
    Time t;
    char str[] = "abcd";
    cout << str << endl;
    revstr(str);
    cout << str << endl;
}

原输出

abcd
dcba
time 7.708e-06

错误尝试与编译报错

尝试将计时代码改为:

std::chrono::duration<std::chrono::nanoseconds> time = end-start;

触发编译错误:

A duration representation cannot be a duration.

解决方案

编译错误的核心原因是std::chrono::duration的模板参数用法错误:第一个参数必须是数值类型(如long long、double),第二个参数是时间周期(如std::nano、std::milli),不能直接传入std::chrono::nanoseconds这类已封装好的duration类型。

以下是三种常用计时单位的正确实现方式:

1. 输出纳秒(整数形式)

直接用预定义的std::chrono::nanoseconds类型接收时间差,它是std::chrono::duration<long long, std::nano>的别名,配合duration_cast做类型转换:

~Time()
{
    auto end = chrono::steady_clock::now();
    auto time = chrono::duration_cast<chrono::nanoseconds>(end - start);
    cout << "time (nanoseconds): " << time.count() << endl;
}

2. 输出毫秒(整数/浮点数可选)

  • 整数毫秒(截断小数部分):
~Time()
{
    auto end = chrono::steady_clock::now();
    auto time = chrono::duration_cast<chrono::milliseconds>(end - start);
    cout << "time (milliseconds): " << time.count() << endl;
}
  • 浮点数毫秒(保留小数精度):
~Time()
{
    auto end = chrono::steady_clock::now();
    chrono::duration<double, std::milli> time = end - start;
    cout << "time (milliseconds): " << time.count() << endl;
}

3. 输出秒(明确格式)

  • 整数秒:
~Time()
{
    auto end = chrono::steady_clock::now();
    auto time = chrono::duration_cast<chrono::seconds>(end - start);
    cout << "time (seconds): " << time.count() << endl;
}
  • 浮点数秒(和原代码效果一致,但语义更清晰):
~Time()
{
    auto end = chrono::steady_clock::now();
    chrono::duration<double, std::ratio<1>> time = end - start;
    // 等价于原代码的chrono::duration<double>,默认周期为秒
    cout << "time (seconds): " << time.count() << endl;
}

额外提示

原代码缺少#include <cstring>头文件,strlen函数依赖该头文件,建议补上以避免编译警告或错误。

内容的提问来源于stack exchange,提问作者KcFnMi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 22:25:30