【问题标题】:Is there any C++ standard class/function which is similar to GetTickCount() on Windows?是否有任何类似于 Windows 上的 GetTickCount() 的 C++ 标准类/函数?
【发布时间】:2014-09-17 09:51:14
【问题描述】:
unsigned int Tick = GetTickCount();

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

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

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

【问题讨论】:

  • 据我所知,没有得到系统启动以来的毫秒数,但相对时间很多。
  • C++ 没有“系统已启动”的概念,所以,不,没有类似的东西。不过,chrono 中有很多东西可以解决您面临的相同问题。我们只需要知道您面临什么问题。
  • @rubenvb: clock_getttime() 是一个 POSIX 标准接口,它不能移植到 Windows,就像 GetTickCount() 不能移植到 Linux 一样,所以建议的副本比副本更“相关” .
  • steady_clock 是最接近的等价物,如果您想要两个任意点之间的经过时间 - 与 system_clock 不同,它不会被调整。但是,如果您特别想要系统启动以来的时间,那就不好了;没有任何标准。

标签: c++ c++11 std chrono gettickcount


【解决方案1】:

您可以在 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() << "ms\n";
}

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

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

1000ms

【讨论】:

    猜你喜欢
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多