tags:

views:

80

answers:

3

Hi,

I am using C language and Linux as my programming platform in embedded device.

My question is, how to correctly retrieve the current processor time(tick). I am using clock() function in time.h and it seems I am getting inconsistent value.

Thanks.

+6  A: 

The clock() function measures the CPU time consumed by your process. It doesn't increment while your process is sleeping or blocked.

If you want a high resolution clock that advances continually, use clock_gettime(CLOCK_MONOTONIC, ..).

caf
+1  A: 

I am not real clear on what, specifically, you are asking. If you want another method to get the time your process is using, I often use getitimer() / setitimer() with ITIMER_PROF versus ITIMER_REAL. I find that can be a bit quirky, however.

Dave
+1  A: 

You may be interested in the LWN article "The trouble with TSC", and the attached comments. While gettimeofday and clock_gettime seem to be the correct thing to go to, there's a lot to consider: performance may vary, there may be consistency issues between different CPUs in multithreaded or multiprocess programs, and the presence of e.g. NTP can mutate the clock value (CLOCK_MONOTONIC will not be affected by NTP, but others may).

Be careful, and make sure you read up on whatever you pursue to make sure it fits your requirements. If you're lucky you're on a fixed hardware and library platform, or you can afford some kinds of inaccuracy or imprecision.

leander
`CLOCK_MONOTONIC` will always go up (at worst it will stand still) If you don't mind being Linux specific, and requiring a kernel newer than 2.6.28, with newish glibc you can use `CLOCK_MONOTONIC_RAW`; NTP doesn't affect it. (I'm not sure what version glibc you'll need to get that constant defined however)
Spudd86