Windows C 上的getTime ofday行为

gettimeofday behavior on windows C++

本文关键字:ofday 行为 getTime 上的 Windows      更新时间:2023-10-16

我编写了一个程序,以在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() << "sn";
    std::cout << d.count() << "msn";

    return 0;
}

查看拆卸您的程序。函数search什么都没有返回,什么也没有改变,因此编译器决定删除评估,因此完全循环。功能主体变为空体并删除了呼叫。