Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 );

?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading