Joy Hyuk Lee
Joy Hyuk Lee

Reputation: 776

Is there any C++ standard class/function which is similar to GetTickCount() on Windows?

unsigned int Tick = GetTickCount();

This code is running only on Windows, but I want to use the C++ Standard library so it can run elsewhere.

I searched std::chrono, but I can't find a function like GetTickCount().

Do you know what I should use from std::chrono?

Upvotes: 7

Views: 10983

Answers (2)

Urmas Rahu
Urmas Rahu

Reputation: 1

One-line answer,

std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count()

Upvotes: 0

Howard Hinnant
Howard Hinnant

Reputation: 218770

You could build a custom chrono clock on top of Windows' GetTickCount(). Then use that clock. In porting, all you would have to do is port the clock. For example, I am not on Windows, but here is what such a port might look like:

#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";
}

On my system, steady_clock happens to return nanoseconds since boot. You may find other non-portable ways of emulating GetTickCount() on other platforms. But once that detail is done, your clock is solid, and the clock's clients don't need to be any wiser about it.

For me this test reliably outputs:

1000ms

Upvotes: 7

Related Questions