I wrote this program that will read from a file some numbers, insert into an array, perform linear search, sort them, and perform binary search (after sorted).
I put the clock functions to measure how long it takes to perform each task mentioned above.
The files are big and have about 5 million numbers. Inserting takes time and is shown by the clock. (Reading from the file is not done in the best way), so does linear search and sorting. However, binary search takes 0 seconds to be performs. Obviously this isn’t right.
I am curios why it is displaying zero for both the time in milliseconds and the number of clock ticks?
I am running in Windows 8.1, ASUS, Intel i-5, 8GB of RAM, 2.4 GHz processor.
This is the output:
$ make
g++ -c -Wall -g search.cpp
g++ -o search search.o
$ ./search <input-5m.in
Time to insert: 26171
Time to Linear Search: 16
Yes!
Time to Sort: 1390
Time to Binary Search in milliseconds: 0
Time to Binary Search in clock ticks: 0
Time to Binary Search printed with "printf()": 0.000000
Yes!
This is the code.
using namespace std;
#include <iostream>
#include <algorithm>
#include <ctime>
#include <cstdio>
#include <iomanip> // std::setprecision
clock_t clock(void);
...
...
...
int main(int argc, char** argv)
{
...
...
...
clock_t startLinear, finishLinear;
double elapsedTimeLinear =0;
startLinear = clock();
bool foundLinear = linearSearch(elements, n , x);
finishLinear = clock();
elapsedTimeLinear = (double)(finishLinear - startLinear)/CLOCKS_PER_SEC*1000;
cout << "Time to Linear Search: " << elapsedTimeLinear << endl;
foundLinear ? std::cout<<"Yes!"<<std::endl : std::cout<<"No!"<<std::endl;
clock_t startSort, finishSort;
double elapsedTimeSort =0;
startSort = clock();
sort(elements, elements+n);
finishSort = clock();
elapsedTimeSort = (double)(finishSort - startSort)/CLOCKS_PER_SEC*1000;
cout << "Time to Sort: " << elapsedTimeSort << endl;
clock_t startBinary, finishBinary;
double elapsedTimeBinary =0, elapsedTimeBinaryTicks=0;
startBinary = clock();
//bool foundBinary = binarySearch(elements, n , x);
bool foundBinary = binary_search(elements, elements+n, x);
finishBinary = clock();
elapsedTimeBinary = (double)(finishBinary - startBinary)/CLOCKS_PER_SEC*1000;
elapsedTimeBinaryTicks = (double)(finishBinary - startBinary);
cout << "Time to Binary Search in milliseconds: " << elapsedTimeBinary << endl;
cout << "Time to Binary Search in clock ticks: " << elapsedTimeBinaryTicks << endl;
printf("Time to Binary Search printed with \"printf()\": %f\n", elapsedTimeBinary);
foundBinary ? std::cout<<"Yes!"<<std::endl : std::cout<<"No!"<<std::endl;