Question:
Why function
int max1(int x,int y)
{
return x>y ? x : y;
}
runs slower than
int max2(int x,int y)
{
return x<y ? y : x;
}
?
I found an article about it even (at the end of the speed comparison table)
Here's my comparison:
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <utility>
#include <ctime>
int max1(int x,int y)
{
return x>y ? x : y;
}
int max2(int x,int y)
{
return x<y ? y : x;
}
int main()
{
std::srand(unsigned(std::time(0)));
const unsigned long long size = 1000000000;
std::vector<std::pair<int,int>> v(size);
std::for_each(v.begin(),v.end(),[](std::pair<int,int>& x){x=std::make_pair(std::rand(),std::rand());});
unsigned int start1 = clock();
for (auto i : v) max1(i.first,i.second);
unsigned int end1 = clock();
std::cout << end1-start1 << std::endl;
unsigned int start2 = clock();
for (auto i : v) max2(i.first,i.second);
unsigned int end2 = clock();
std::cout << end2-start2 << std::endl;
}
Answer:
There is no difference in performance of the above functions and there cannot be any (*). They can be converted to absolutely identical assembly code, which is what, for example, gcc does. clang and MSVC generate different conditional move instructions, but their difference is only in the comparison instruction (less than and greater than-equal), which is the same in digital logic, so there will be no difference.
(*) The difference in performance can only be in the following cases:
- Incorrect measurements
- Compiler error