4
unsigned int Tick = GetTickCount();

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

我搜索std::chrono了,但我找不到像GetTickCount().

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

4

1 回答 1

4

您可以chrono在 Windows 的GetTickCount(). 然后使用那个时钟。在移植中,您所要做的就是移植时钟。例如,我不在 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() << "ms\n";
}

在我的系统上,steady_clock自启动后恰好返回纳秒。GetTickCount()您可能会在其他平台上找到其他不可移植的模拟方式。但是一旦完成了这个细节,你的时钟就稳定了,时钟的客户不需要更聪明。

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

1000ms
于 2014-07-25T15:27:58.627 回答