是否有类似于Windows上的GetTickCount()的c++标准类/函数?
Is there any C++ standard class/function which is similar to GetTickCount() on Windows?
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
相关文章:
- 使用CMake检测支持的C++标准
- 如何理解C++标准N3337中的expr.const.cast子句8
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 编译标准库类型
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 编译器如何在使用SFINAE的函数和标准函数之间确定两者是否可行
- 铸造标准::有没有回到原来的类型
- 标准 N3337 5.2.10 第 7 条中的C++"类型"是什么意思?
- this_thread::sleep_for和计时时钟之间的关系是否由C++11标准指定
- 标准库类型的赋值运算符的引用限定符
- 标准是否严格定义了该程序应该如何编译?
- 如何从Windows应用程序输出到标准?
- 安全到标准:移动会员?
- 如何正确将字符串转换为标准::时间::system_clock::time_point?
- 这是否符合C++标准:双响双响,例如!!(-0.0).
- 标准::变体的赋值运算符
- 捕获标准输出以压缩并使用 CTRL-C 中断会给出损坏的 zip 文件
- 如何在 Mac 上使用 c++17 并行标准库算法?
- 强枚举类型定义:Clang Bug 还是 C++11 标准不确定性?
- 并行标准::复制复杂性