Tempted to write code like this on Linux?


clock() measures the CPU time taken by the current process, not the absolute passage of time ("wall time"). On most systems, the time spent in a sleep() or usleep() call does not count towards the process's runtime; the OS simply diverts all of its attention to other processes whilst your program waits. The program above could feasibly run for far longer than thirty seconds… perhaps years.

(I'm ignoring here that sleep() will actually wait for at least the duration you give it; sleep(1) is allowed to sleep from anywhere between one second and ten years. Of course, realistically, you'll get close to a second's wait on a sane platform. I'm also ignoring that clock() wraps around, and will do so every 72 minutes that complies with POSIX by having a CLOCKS_PER_SEC value of 1000000.)

You're better off using a function like plain old time() or gettimeofday() (which can usually give you microseconds' resolution) if you want to measure the wall time: