Lee*_*Lee 7 c++ std gettickcount c++11 c++-chrono
unsigned int Tick = GetTickCount();
Run Code Online (Sandbox Code Playgroud)
该代码仅在 Windows 上运行,但我想使用 C++ 标准库,以便它可以在其他地方运行。
我搜索过std::chrono,但找不到类似的功能GetTickCount()。
你知道我应该使用什么吗std::chrono?
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";
}
Run Code Online (Sandbox Code Playgroud)
在我的系统上,steady_clock自启动后恰好返回纳秒。您可能会发现在其他平台上进行模拟的其他不可移植的方式GetTickCount()。但是,一旦完成了这些细节,您的时钟就变得可靠了,并且时钟的客户不需要对此有任何了解。
对我来说,这个测试可靠地输出:
1000ms
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10172 次 |
| 最近记录: |