Windows C ++上的gettimeofday行为

时间:2018-02-13 17:30:40

标签: c++

我编写了一个程序来查找10000000数字向量中的数字,这是一个非常大的向量。但问题是我得到了

  

线性搜索所花费的时间等于0 ms

当我搜索向量中的任何数字时。我期望它应该是毫秒或秒,虽然它是一个很大的载体。

任何帮助都将受到高度赞赏。

#include <iostream>
#include <sys/time.h>
#include <vector>
#include <chrono>
using namespace std;


void search(vector<int>& num , int key)
{
    for(int i = 0; i < num.size(); i++)
    {
        if(num[i] == key)
        {
            cout << "Found"  << endl;
            break;
        }
    }
}


int main()
{
    vector<int> num;

    for(int i= 0; i < 100000; i++)
        num.push_back(i);

    cout << "Enter the key : " ;
    int key;
    cin >> key;

    typedef std::chrono::high_resolution_clock Time;
    typedef std::chrono::milliseconds ms;
    typedef std::chrono::duration<float> fsec;
    auto t0 = Time::now();

    //struct timeval t1, t2;
    //gettimeofday(&t1, NULL);
    search(num , key);
    //gettimeofday(&t2, NULL);
    //double timeDiff = (t2.tv_sec - t1.tv_sec)*1000.0 + (t2.tv_usec - t1.tv_usec)/1000.0;
    //cout << "Time taken for linear search " << timeDiff << " ms" << endl;
    auto t1 = Time::now();
    fsec fs = t1 - t0;
    ms d = std::chrono::duration_cast<ms>(fs);
    std::cout << fs.count() << "s\n";
    std::cout << d.count() << "ms\n";


    return 0;

}

1 个答案:

答案 0 :(得分:3)

看看你的程序被反汇编了。函数search什么都不返回,什么都不改变,因此编译器决定删除评估,因此根本就是循环。函数体变空,其调用被删除。

相关问题