unsigned int Tick = GetTickCount();
此代码仅在 Windows 上运行,但我想使用 C++ 标准库,以便它可以在其他地方运行。
我搜索了
std::chrono
,但找不到像GetTickCount()
这样的功能。
你知道我应该使用什么吗
std::chrono
?
您可以在 Windows 的
chrono
之上构建自定义 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
我使用这样的 chrono 来达到同样的目的:
using namespace std::chrono;
duration_cast<milliseconds(high_resolution_clock::now().time_since_epoch()).count();