是否有类似于Windows上的GetTickCount()的c++标准类/函数?

Is there any C++ standard class/function which is similar to GetTickCount() on Windows?

本文关键字:标准 c++ 函数 类似于 Windows 上的 GetTickCount 是否      更新时间:2023-10-16
unsigned int Tick = GetTickCount();

此代码仅在Windows上运行,但我想使用c++标准库,以便它可以在其他地方运行。

我搜索了std::chrono,但是我找不到像GetTickCount()这样的函数。

你知道我应该用std::chrono中的什么吗?

您可以在Windows的GetTickCount()之上构建一个自定义的chrono时钟。那就用那个钟。在移植中,你所要做的就是移植时钟。例如,我不是在Windows上,但是这样的端口可能是这样的:

#include <chrono>
// simulation of Windows GetTickCount()
unsigned long long
GetTickCount()
{
    using namespace std::chrono;
    return duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
}
// Clock built upon Windows GetTickCount()
struct TickCountClock
{
    typedef unsigned long long                       rep;
    typedef std::milli                               period;
    typedef std::chrono::duration<rep, period>       duration;
    typedef std::chrono::time_point<TickCountClock>  time_point;
    static const bool is_steady =                    true;
    static time_point now() noexcept
    {
        return time_point(duration(GetTickCount()));
    }
};
// Test TickCountClock
#include <thread>
#include <iostream>
int
main()
{
    auto t0 = TickCountClock::now();
    std::this_thread::sleep_until(t0 + std::chrono::seconds(1));
    auto t1 = TickCountClock::now();
    std::cout << (t1-t0).count() << "msn";
}

在我的系统上,steady_clock从引导开始返回纳秒。您可能会发现在其他平台上模拟GetTickCount()的其他不可移植的方法。但是,一旦完成了这些细节,您的时钟就可靠了,时钟的客户端不需要对此有任何了解。

对我来说,这个测试可靠地输出:

1000ms