NTDaemon
NTDaemon

Reputation: 23

which of the clock is best to calculate the start-time endtime among CLOCK_REALTIME CLOCK_MONOTONIC

I want to calculate time elapsed by a particular function by getting starting time and ending time, then calculate the difference between them.

I am confused between the two clocks CLOCK_REALTIME and CLOCK_MONOTONIC. Which of these will give me the correct value of time in any unit (seconds, nanoseconds, or milliseconds)?

Upvotes: 2

Views: 126

Answers (1)

bpgeck
bpgeck

Reputation: 1624

So CLOCK_MONOTONIC is the elapsed time since some undefined point of time in the past (for linux I believe this is boot time).

CLOCK_REALTIME, however, is essentially the computer's interpretation of the current real-world time. As a result, this time changes according to your computers internal clock; if you manually change your machine's time, CLOCK_REALTIME will change.

Thus, CLOCK_MONOTONIC is best for the task of finding elapsed time. Since it calculates the time elapsed since some arbitrary point in time, though, you will probably need to save the CLOCK_MONOTONIC values at both the beginning and end of your function and subtract them to determine the elapsed time.

Upvotes: 2

Related Questions