如何在不受系统时间变化影响的情况下测量经过的时间

How to measure elapsed time without being affected by changes in system time

我想以秒为单位测量经过的时间。用 std::chrono::steady_clock 我做到了。然而,它受到系统时间变化的影响。

steady_clock 不是应该不受系统时间变化的影响吗?

我该怎么做?

代码如下:

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

std::chrono::steady_clock::time_point t = std::chrono::steady_clock::now();

/* Change system time */
std::time_t tnow = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
tnow -= 20;
std::cout << "stime: " << stime(&tnow) << std::endl;
/********************************************************/

sleep(5);
std::chrono::steady_clock::time_point t2 = std::chrono::steady_clock::now();
std::cout << "ELAPSED: " << std::chrono::duration_cast<std::chrono::seconds>(t2-t).count() << std::endl;

结果:

stime: 0
ELAPSED: -15

我想得到的是:

ELAPSED: 5

编辑:

我添加了 C 标签,因为它似乎是内核(或板的 buildroot)错误。那么,如果没有 chrono 我怎么能做到这一点呢?我的意思是,以直接的方式(无需观察系统时间变化)。

chrono 之前人们的生活如何?

您可以向供应商提交错误。

From the standard:

Objects of class steady_­clock represent clocks for which values of time_­point never decrease as physical time advances and for which values of time_­point advance at a steady rate relative to real time. That is, the clock may not be adjusted.

如果您可以在您的系统上找到可靠的单调时间来源,您可以轻松地将该来源包装在自定义 chrono::clock 中,随后仍然可以使用类型安全的计时系统。例如:

#include <chrono>

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

    static time_point now() noexcept
    {
        using namespace std::chrono;
        timespec ts;
        clock_gettime(CLOCK_MONOTONIC, &ts);
        return time_point{seconds{ts.tv_sec} + nanoseconds{ts.tv_nsec}};
    }
};

现在你可以这样说了:

MyClock::time_point t = MyClock::now();
// ...
MyClock::time_point t2 = MyClock::now();
std::cout << "ELAPSED: " << std::chrono::duration_cast<std::chrono::seconds>(t2-t).count() << std::endl;