Speed ​​Comparison of Two Cycle Styles

I read about STL algorithms, and the book says that algorithms like find use a while loop, not a for loop, because it is minimal, efficient, and uses one smaller variable. I decided to do some testing, and the results did not really match.

Informing consistently performs better than while. At first, I just tested it by returning 10,000 ints back to the vector, and then using find to get one value from it and return it to the iterator. I timed it and gave this time.

Then I decided to change it so that the forfind and whilefind functions are used several times (in this case 10,000 times). However, loop search was still higher in performance than search. Can someone explain this? Here is the code.

#include "std_lib_facilities.h"
#include<ctime>

template<class ln, class T>
ln whilefind(ln first, ln last, const T& val)
{
    while (first!=last && *first!=val) ++first;
    return first;
}

template<class ln, class T>
ln forfind(ln first, ln last, const T& val)
{
    for (ln p = first; p!=last; ++p)
        if(*p == val) return p;
    return last;
}

int main()
{
    vector<int> numbers;
    vector<int>::iterator whiletest;
    vector<int>::iterator fortest;
    for (int n = 0; n < 10000; ++n)
        numbers.push_back(n);

    clock_t while1 = clock();   // start
    for (int i = 0; i < 10000; ++i)
        whiletest = whilefind(numbers.begin(), numbers.end(), i);
    clock_t while2 = clock();   // stop

    clock_t for1 = clock(); // start
    for (int i = 0; i < 10000; ++i)
        fortest = forfind(numbers.begin(), numbers.end(), i);
    clock_t for2 = clock(); // stop

    cout << "While loop: " << double(while2-while1)/CLOCKS_PER_SEC << " seconds.\n";
    cout << "For loop: " << double(for2-for1)/CLOCKS_PER_SEC << " seconds.\n";
}

while , 78 , - 67 .

+3
1
if(*p = val) return p;

==. forfind , 0 1-9999.

+11

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


All Articles