SuperUser
SuperUser

Reputation: 341

c++ Linux TickCount

Is there a similar function like GetTickCount() for Linux?

I´ve tried out some other sutff, but they didn´t work at all.

So it should return the exact time in milliseconds since startup.

Upvotes: 4

Views: 13904

Answers (3)

hd1
hd1

Reputation: 34657

clock_gettime with CLOCK_MONOTONIC is the magic incantation you seem to be looking for. Sample code, untested:

struct timespec *t;
t = (struct timespec *)malloc(sizeof(t)); 
clock_gettime(CLOCK_MONOTONIC, t);

Let me know how you get on. I'm not on Linux at the moment, hence this is just conjecture from the man page I pointed to.

Upvotes: 2

Simon
Simon

Reputation: 399

/// Returns the number of ticks since an undefined time (usually system startup).
static uint64_t GetTickCountMs()
{
    struct timespec ts;

    clock_gettime(CLOCK_MONOTONIC, &ts);

    return (uint64_t)(ts.tv_nsec / 1000000) + ((uint64_t)ts.tv_sec * 1000ull);
}

Also useful...

/// Computes the elapsed time, in milliseconds, between two 'timespec'.
inline uint32_t TimeElapsedMs(const struct timespec& tStartTime, const struct timespec& tEndTime)
{
   return 1000*(tEndTime.tv_sec - tStartTime.tv_sec) +
          (tEndTime.tv_nsec - tStartTime.tv_nsec)/1000000;
}

Upvotes: 6

serengeor
serengeor

Reputation: 69

hmm well compiler says it doesn´t exists, but I included time.h

Does it give you a compiler or a linker error? If you get a linker error, it might be because you haven't linked with 'rt' library.

Upvotes: 0

Related Questions