Home > OS >  Why iterative std::max with 2 constants is faster than std::max with initializer list?
Why iterative std::max with 2 constants is faster than std::max with initializer list?

Time:07-07

Compiler : Visual Studio 2019 , Optimization : (Favor Speed)(/O2)

In a loop (over 1 million cycles), I use std::max to find the maximum element among 10 elements. When I use std::max iteratively, like

using namespace std;
using namespace chrono;
auto start = high_resolution_clock::now();
for(int i=0;i<1000000;i  )
    out = max(arr[i],max(arr2[i],max(....);
auto end= high_resolution_clock::now();
cout << duration_cast<milliseconds>(end-start).count()<<endl;

is much faster than

using namespace std;
array<int,10> arrs;
auto start = high_resolution_clock::now();
for(int i=0;i<1000000;i  )
    {
    arrs = {arr[i],arr2[i],....};
    out = max(arrs);
    }
auto end= high_resolution_clock::now();
cout << duration_cast<milliseconds>(end-start).count()<<endl;

Why is that ? This is actually not a specific question for the example above.

Why

constexpr const T& max( const T& a, const T& b );

is much faster than

template< class T >
constexpr T max( std::initializer_list<T> ilist );

?

CodePudding user response:

You are copying all of the array elements when you are constructing an initializer list, which is going to incur more overhead.

  • Related