Getting the System tick count with basic C++?

Donal Rafferty picture Donal Rafferty · Apr 29, 2010 · Viewed 35.3k times · Source

I essentially want to reconstruct the getTickCount() windows function so I can use it in basic C++ without any non standard libraries or even the STL. (So it complies with the libraries supplied with the Android NDK)

I have looked at

clock()

localtime

time

But I'm still unsure whether it is possible to replicate the getTickCount windows function with the time library.

Can anyone point me in the right direction as to how to do this or even if its possible?

An overview of what I want to do:

I want to be able to calculate how long an application has been "doing" a certain function.

So for example I want to be able to calculate how long the application has been trying to register with a server

I am trying to port it from windows to run on the linux based Android, here is the windows code:


int TimeoutTimer::GetSpentTime() const
{
if (m_On)
{
    if (m_Freq>1)
    {
        unsigned int now;
        QueryPerformanceCounter((int*)&now);
        return (int)((1000*(now-m_Start))/m_Freq);
    }
    else
    {
        return (GetTickCount()-(int)m_Start);
    }
}
return -1;
}

Answer

fadden picture fadden · Apr 30, 2010

On Android NDK you can use the POSIX clock_gettime() call, which is part of libc. This function is where various Android timer calls end up.

For example, java.lang.System.nanoTime() is implemented with:

struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
return (u8)now.tv_sec*1000000000LL + now.tv_nsec;

This example uses the monotonic clock, which is what you want when computing durations. Unlike the wall clock (available through gettimeofday()), it won't skip forward or backward when the device's clock is changed by the network provider.

The Linux man page for clock_gettime() describes the other clocks that may be available, such as the per-thread elapsed CPU time.