Home > database >  Is my algorithm genuinely this fast? Or is my clock incorrectly coded
Is my algorithm genuinely this fast? Or is my clock incorrectly coded

Time:06-24

#include <iostream>
#include <chrono>
#include <vector>
#include <algorithm>

template<class Type>
Type lnSearch(std::vector<Type>& Data, Type Target) {
    for (typename std::vector<Type>::iterator Iterator = Data.begin(); Iterator != Data.end(); Iterator  ) {
        if (*Iterator == Target)    return *Iterator;
        else   continue;
    }
    return Type{};
}

int main(void) {
    std::vector<int> data;
    for (int i = 0; i < 100000000; i  ) {
        data.push_back(i);
    }
    std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
    std::cout << lnSearch(data, 99999999);
    std::chrono::high_resolution_clock::time_point stop = std::chrono::high_resolution_clock::now();
    std::chrono::seconds sduration = std::chrono::duration_cast<std::chrono::seconds>(stop - start);
    std::chrono::milliseconds msduration = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start);
    std::cout << "Time taken by function: " << sduration.count() << "." << msduration.count() << "s" << std::endl;
    return 0;
}

Is my algorithm genuinely fast, is my clock coded incorrectly or is my perception of fast wrong?

in Release mode on vs22, it runs through 100,000,000 iterations in a range of 0.133s - 0.344s

CodePudding user response:

Since the if statement in your code is very predictable, the processor can optimize this code very well.
An in depth explanation can be found here:
enter image description here

  •  Tags:  
  • c
  • Related