为什么 chrono::system_clock 返回微秒而clock_gettime 返回纳秒

rtu*_*tur 2 c++ nanotime c++-chrono

std::chrono::system_clock::time_since_epoch().count() 给出了以微秒为单位的结果。

我想要当前时间(以纳秒为单位)。但我不能使用 high_resolution_clock 因为在我的系统上它是 stable_clock (单调时钟)的别名。

我知道我的系统具有纳秒能力,因为如果我使用clock_gettime(CLOCK_REALTIME, &ts),我将获得正确的纳秒分辨率纪元时间。

我如何告诉 std::chrono 使用纳秒分辨率?我想避免使用clock_gettime 并坚持使用cpp 包装器。

How*_*ant 5

我如何告诉 std::chrono 使用纳秒分辨率?

这听起来是编写您自己的自定义时钟的一个很好的用途。这比听起来容易得多:

#include <time.h>
#include <chrono>

struct my_clock
{
    using duration   = std::chrono::nanoseconds;
    using rep        = duration::rep;
    using period     = duration::period;
    using time_point = std::chrono::time_point<my_clock>;
    static constexpr bool is_steady = false;

    static time_point now()
    {
        timespec ts;
        if (clock_gettime(CLOCK_REALTIME, &ts))
            throw 1;
        using sec = std::chrono::seconds;
        return time_point{sec{ts.tv_sec}+duration{ts.tv_nsec}};
    }
};
Run Code Online (Sandbox Code Playgroud)

只需now()拨打.clock_gettimeCLOCK_REALTIME然后将返回结果打包成一个chrono::time_point带有nanoseconds分辨率的文件。

警告,我刚刚在 macOS 上尝试过此操作并now()连续调用了两次。它每次打印出相同的纳秒数。而且调用不可能在一纳秒内执行。所以我得到的是纳秒精度,但不是纳秒精度。

如果您想my_clock参与 C++20std::chrono::clock_cast设施(如 Nicol Bolas 在下面的评论中建议的那样),请将这两个静态成员函数添加到my_clock

template<typename Duration>
static
std::chrono::time_point<std::chrono::system_clock, Duration>
to_sys(const std::chrono::time_point<my_clock, Duration>& tp)
{
    return std::chrono::time_point<std::chrono::system_clock, Duration>
        {tp.time_since_epoch()};
}

template<typename Duration>
static
std::chrono::time_point<my_clock, Duration>
from_sys(const std::chrono::time_point<std::chrono::system_clock, Duration>& tp)
{
    return std::chrono::time_point<my_clock, Duration>{tp.time_since_epoch()};
}
Run Code Online (Sandbox Code Playgroud)

现在你可以这样说:

cout << clock_cast<system_clock>(my_clock::now()) << '\n';
Run Code Online (Sandbox Code Playgroud)

您还可以clock_cast往返于参与该设施的所有clock_cast其他 C++20 和自定义时钟。