user12050586
user12050586

Reputation:

Using clock() as a timer in c

I have the following basic three lines of code to see if the clock is timing things correctly:

#include <unistd.h>
#define wait(seconds) sleep( seconds )

printf("%lu\n", clock());
wait(2);
printf("%lu\n", clock());

wait() seems to be working fine -- as when I run it, it 'feels' like it is pausing for 2s.

However, here is what the print command gives:

253778

253796

And so when I do something like:

(double) (clock() - t0) / CLOCKS_PER_SEC

It gives me useless results.

What is clock() doing here that I'm not understanding, and how can I fix this to get an accurate timer?

Upvotes: 0

Views: 843

Answers (2)

Kaz
Kaz

Reputation: 58667

ISO C says that the "clock function returns the implementation's best approximation to the processor time used by the program since the beginning of an implementation-defined era related only to the program invocation."

In other words, it is not a real-time clock.

On platforms where C code runs as a process that can be put to sleep by an underlying operating system, a proper implementation of clock stops counting when that happens.

ISO C provides a function time that is intended to provide calendar time, encoded as a time_t arithmetic value. The difftime function computes the difference between two time_t values as a floating-point value of type double measuring seconds. On many systems, the precision of time_t is no better than one second, though.

There are POSIX functions for finer resolution time such as gettimeofday, or clock_gettime (with a suitable clock type argument).

Upvotes: 2

Ankush
Ankush

Reputation: 1081

If you have a read of the man page for clock(), you will see the following listed in the notes:

On several other implementations, the value returned by clock() also includes the times of any children whose status has been collected via wait(2) (or another wait-type call). Linux does not include the times of waited-for children in the value returned by clock(). The times(2) function, which explicitly returns (separate) information about the caller and its children, may be preferable.

So clock() doesn't always include the time taken by something like wait() on all implementations. If you are on Linux, you may want to take a look at the times() function, defined in sys/times.h, as it returns a structure including the time (in clock ticks) taken by children (thus functions like wait() are included).

Upvotes: 1

Related Questions