Gepard
Gepard

Reputation: 499

clock() not working on some platforms

I have problems with clock() on a machine running 32-bit version of Debian 6.0.3. It seems to always return 0. When using this example program, I get following output:

Calculating...
The number of primes lower than 100,000 is: 9592
It took me 0 clicks (0.000000 seconds).

However, the same system running in VMWare virtual machines produces expected output:

It took me 60000 clicks (0.060000 seconds).

What can be the problem here? Are there any better portable ways to benchmark produced code and processing power of the host? (I need this for quick and dirty bcrypt benchmarking).

Upvotes: 1

Views: 136

Answers (1)

Jens Gustedt
Jens Gustedt

Reputation: 78993

Perhaps your machine is just too fast, clock has a resolution of micro-seconds.

There is no other portable way to do this within C alone, and even this can be questioned since a large software vendor has clock returning wallclock time and not cpu time.

Since you are on a POSIX system, I'd suggest to use the tools that that provides, namely clock_gettime with the clocks CLOCK_PROCESS_CPUTIME_ID or CLOCK_THREAD_CPUTIME_ID. Modern Linux supports them well.

If you need a function that works for all the three (Linux, Windows, Mac) use the POSIX version as a default and create fallbacks for Windows and Mac. Both don't seem to conform to the standards; Windows not even to the C standard, and Mac not to modern POSIX. This makes you maintain two exception codes, which would not be too difficult, I'd hope.

Upvotes: 1

Related Questions