【问题标题】:How to make std chrono output in milliseconds or nanoseconds? [duplicate]如何以毫秒或纳秒为单位制作 std chrono 输出? [复制]
【发布时间】:2023-02-07 23:53:51
【问题描述】:
#include <iostream>
#include <chrono>

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;
}

以上输出:

time 7.708e-06

我们应该如何以毫秒、纳秒或秒为单位进行转换?

我试过

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

但它说:

持续时间表示不能是持续时间。

【问题讨论】:

标签: c++ time


【解决方案1】:

使用std::chrono::duration_cast()

#include <chrono>
#include <iostream>

int main()
{
    std::chrono::duration<double> time{7.708e-06};

    auto nanos = std::chrono::duration_cast<std::chrono::nanoseconds>(time);

    std::cout << nanos.count() << '
';

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多