【问题标题】:how to calculate the time taken to search for a word using binary search [duplicate]如何计算使用二进制搜索搜索单词所需的时间[重复]
【发布时间】:2019-08-21 06:50:39
【问题描述】:
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;
}

如果我想知道这段代码需要多长时间才能在data 中找到一个单词,这是一个string 类型的向量,并且它加载了单词。

【问题讨论】:

  • 测量,获取前后时钟时间,并减去。要计算,需要更多信息(什么目标系统 - 硬件、指令集、使用指令的速度、内存等)。无论是计算还是测量,都需要指定案例(例如,多少字,多大的字等)

标签: c++ file binary-search


【解决方案1】:

std::chrono::high_resolution_clock 是最准确的,因此用于测量执行时间。

//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); 

【讨论】:

  • 你能解释一下吗
  • 检查更新的答案
  • 它属于哪个库?
  • @Muhammadbakr 属于c++标准库(最低标准符合c++11)。
  • 不幸的是我使用的是 c++98
【解决方案2】:

您可以为此使用std::chrono::high_resolution_clock

// 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";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多