Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top