What about this code. Can anyone explain the bolded statements:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
#define MAX_ELEMENT 20000
int binsearch(int x, int v[], int n) {
int low, mid, high;
low = 0;
high = n - 1;
while ( low <= high ) {
mid = (low+high) / 2;
if ( x < v[mid] )
high = mid - 1;
else if ( x > v[mid] )
low = mid + 1;
else
return mid;
}
return -1;
}
int binsearch2(int x, int v[], int n) {
int low, high, mid;
low = 0;
high = n - 1;
mid = (low+high) / 2;
while ( low <= high && x != v[mid] ) {
if ( x < v[mid] )
high = mid - 1;
else
low = mid + 1;
mid = (low+high) / 2;
}
if ( x == v[mid] )
return mid;
else
return -1;
}
int main(int argc, char *argv[])
{
int testdata[MAX_ELEMENT];
clock_t time_taken;
int i, index;
for ( i = 0; i < MAX_ELEMENT; ++i )
testdata[i] = i;
int n = 2500;
/* 100 000 iterations for binsearch */
for ( i = 0, time_taken = clock(); i < 100000; ++i )
{
index = binsearch(n, testdata, MAX_ELEMENT);
}
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);
/* 100 000 iterations for binsearch2 */
for ( i = 0; i < 100000; ++i )
{
index = binsearch(n, testdata, MAX_ELEMENT);
}
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);
system("PAUSE");
return 0;
}
How exactly does clock_t works? What sort of a variable is that?
What is stored into time_taken exactly?
How does clock() function works? It counds processor ticks after each statements?