c++ - 计算二分搜索的运行时间

标签 c++

以下二进制搜索程序使用 GetTickCount() 返回 0 毫秒的运行时间,无论在给定值列表中设置的搜索项有多大。

有没有其他方法可以获取运行时间进行比较?

代码如下:

#include <iostream>
#include <windows.h>
using namespace std;

int main(int argc, char **argv)
{
        long int i = 1, max = 10000000;
        long int *data = new long int[max];
        long int initial = 1;
        long int final = max, mid, loc = -5;
        for(i = 1; i<=max; i++)
        {
            data[i] = i;
        }

        int range = final - initial + 1;
        long int search_item = 8800000;

        cout<<"Search Item :- "<<search_item<<"\n";

        cout<<"-------------------Binary Search-------------------\n";
        long int start = GetTickCount();
        cout<<"Start Time : "<<start<<"\n";

        while(initial<=final)
        {
            mid=(initial+final)/2;

            if(data[mid]==search_item)
            {
                loc=mid;
                break;
            }

            if(search_item<data[mid])
                final=mid-1;

            if(search_item>data[mid])
                initial=mid+1;
        }
        long int end = GetTickCount();
        cout<<"End Time : "<<end<<"\n";
        cout << "time: " << double(end - start)<<" milliseconds \n";
        if(loc==-5)
            cout<<" Required number not found "<<endl;
        else
            cout<<" Required number is found at index "<<loc<<endl;
        return 0;   
}

最佳答案

您的代码如下所示:

int main()
{
    // Some code...

    while (some_condition)
    {
        // Some more code...
        // Print timing result
        return 0;
    }
}

这就是您的代码打印零时间的原因,您只执行一次循环迭代然后退出程序。

关于c++ - 计算二分搜索的运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34980804/

相关文章:

c++ - C/C++ 有哪些突变测试框架?

c++ - 在分层 block 中使用 gr::fec::code::cc_encoder 类

c++ - 为包含 STL 类的链表结构释放内存

c++ - 调试断言失败 : invalid iterators

c++ - 内存障碍,不确定我是否可以轻松使用?

c++ - 从 Objective C 调用带有回调的 C++ 方法

c++ - .so 文件没有正确的依赖关系为什么它工作

c++ - 在 UWP 中使用自定义视频效果

C++ 改变实例变量

c++ - 使用反射在 protobuf 中设置重复字段