0

I am on the K&R book and on exercise 3-1. I think my "time.h" library is broken. At first I thought my code was wrong but when I checked the solutions to the exercise on the net, they don't work either.

The problem:

The program output always shows zero seconds and the 'clocks' are sometimes are exchanged:

Output 1:
    Element -1 not found.
    binsearch() took 10000 clocks (0 seconds)
    Element -1 not found.
    binsearch2() took 20000 clocks (0 seconds)

Output 2:
    Element -1 not found.
    binsearch() took 20000 clocks (0 seconds)
    Element -1 not found.
    binsearch2() took 10000 clocks (0 seconds)

The purpose of the program is to compare the two functions in terms of speed. How do I compare this?

Here is the test code:

 for ( i = 0, time_taken = clock(); i < 100000; ++i ) {
    index = binsearch(n, testdata, MAX_ELEMENT);   /* all this code is duplicated with a
}                                                     call to binsearch2 instead */
time_taken = clock() - time_taken;

if ( index < 0 )
    printf("Element %d not found.\n", n);
else
    printf("Element %d found at index %d.\n", n, index);

printf("binsearch() took %lu clocks (%lu seconds)\n",
       (unsigned long) time_taken,
       (unsigned long) time_taken / CLOCKS_PER_SEC);

I tried this program in both Linux and Windows.

2
  • No it's not it. If you are suggesting of lowering the iterations to 10-20k the output goes to '0 clocks' and still 0 seconds.
    – 1der
    Feb 8, 2012 at 11:27
  • Sorry, mistyped. On the contrary, you need to increase the number of iterations by a large factor (at least as many interations as CLOCKS_PER_SEC).
    – Mat
    Feb 8, 2012 at 11:29

1 Answer 1

1

Maybe CLOCKS_PER_SEC=1000000 in your system.

So time_taken/CLOCKS_PER_SEC gives 0 as expected.

Change your code to double(time_taken)/CLOCKS_PER_SEC to get floating-point.

2
  • Which is very likely, posix demands that CLOCKS_PER_SEC=1000000. @1der, no there isn't. Convert the clock ticks to miliseconds instead of seconds. (Note, clock() is different on linux and windows. on linux, clock() measures CPU time, on windows it measures wall clock time)
    – nos
    Feb 8, 2012 at 11:28
  • Both of you are right, they both finish at a fraction of a second and because the output was formatted to be a whole number, it truncates to zero. Thanks! :)
    – 1der
    Feb 8, 2012 at 11:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.