A linear search on the vector [i] yealds 0ms response, while vector.at (i) yealds time

I have to add: I call my linear search 15,000 times, and the lowest range that I look up is up to 50,000 with each iteration. Thus, at the first iteration, there are 15,000 * 50,000 requests. This should take more than 0 ms.

I have this basic Linear search:

bool linearSearch(std::vector<int>&primes, int number, int range) {

    for (int i = 0; i < range; i++) {
        if (primes[i] == number)
            return true;
    }
    return false;
}

I use time:

void timeLinearSearch(std::vector<int>& primes) {
    clock_t start, stop;
    size_t NRND = 15000;    //  15000 primes per clock

    for (int N = 50000; N <= 500000; N += 50000)    // increase by 50k each iteration
    {
        for (int repeat = 0; repeat < 5; repeat++) {
            start = clock();
            for (int j = 0; j < NRND; j++) {
                linearSearch(primes, rand(), N);
            }
            stop = clock();
            std::cout << stop - start << ", " << N << std::endl;
        }

    }
}

The problem is that the time is 0 ms. The primes vector has approximately 600,000 elements in it, so the search remains within the range.

In a linear search, if I change:

if(primes[i] == number)

at

if(primes.at(i) == number)

then I get the time> 0 taken for the search.

I compared my linear search with primes.at (i) with std :: find ():

for (int j = 0; j < NRND; j++) {
    std::find(primes.begin(), primes.begin() + N, rand());
}

and it is about 200 ms faster than my .at () find.

Why does my search with std :: vector [i] give me 0ms time?

+4
3

linearSearch, , operator[], . .

at(..), , (, ), .

, , , , :

int count = 0;
for (int j = 0; j < NRND; j++) {
    count += linearSearch(primes, rand(), N);
}
std::cout << stop - start << ", " << N << " " << count << std::endl;
+8

, ; , . , , :

[i] , i , at(i) .

: [].

+3

, . "rand()",

( N ): [N/10], [N/2], (3 * N/4),... ( +1, , )

Caution, if your array of primes is sorted in ascending order, you might want to return false if primes [i]> rather than go through the entire array (or even do a dichotomy search), unless you just look. at () rating

0
source

Source: https://habr.com/ru/post/1652609/


All Articles