0
int Binary_search()
{
    string word;
    cout << "Enter The Word You Want To Find : ";
    cin >> word;
    int start = 0, end = data.size() - 1;
    int mid, i = 0, counter = 0;
    while (start <= end)
    {
        mid = (end + start) / 2;
        if (data[i] == word)
            return i;

        else if (data[i] > word)
            end = mid - 1;

        else
            start = mid + 1;

        counter++;
        i++;
    }
    return -1;
}

if i wanna to know how much time this code would take to find a word in data which is a vector of type string and it loaded with words.

  • To measure, obtain clock times before and after, and subtract. To calculate, more information would be needed (what target system - hardware, instruction set, speed of used instructions, memory, etc). Whether calculating or measuring, the cases would need to be specified (e.g. how many words, what size words, etc etc) – Peter Mar 30 '19 at 14:47

2 Answers2

1

The std::chrono::high_resolution_clock is the most accurate and hence it is used to measure execution time.

//Get the timepoint before the function is called
auto start = high_resolution_clock::now(); 
// Binary search ()
// Get ending timepoint..ie after you function is called
auto stop = high_resolution_clock::now(); 

// Get duration. Substart timepoints to  
// get durarion. To cast it to proper unit 
// use duration cast method 
auto duration = duration_cast<microseconds>(stop - start); 
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Mahendra suthar
  • 401
  • 5
  • 18
1

You can use std::chrono::high_resolution_clock for that.

// get start time
auto start = std::chrono::high_resolution_clock::now();

// do some work
Binary_search();

// get end time
auto end = std::chrono::high_resolution_clock::now();

// calculate difference as double value in seconds
std::chrono::duration<double> diff = end-start;
// print the measured value
std::cout << "Time taken : " << diff.count() << " seconds\n";
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Oliort UA
  • 1,568
  • 1
  • 14
  • 31