We often need to calculate the maximum/minimum value of a set of numbers. if-else, ?: and min()/max() are three methods we usually use to achieve the goal. In this post, I compare the efficiency among them. Here is the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <algorithm>
#include <time.h>
#include <vector>
#include <cstdlib>
using namespace std;
int main(){
int pair_num;
cout << "Please input the number of pairs to be compared:" << endl;
cin >> pair_num;
vector<vector<int>> pairs;
for(int i = 0; i < pair_num; ++i){
vector<int> pair;
pair.push_back(rand());
pair.push_back(rand());
pairs.push_back(pair);
}
long result = 0;
clock_t start = clock();
for(auto pair: pairs){
if(pair[0] > pair[1]){
result += pair[0];
}
else{
result += pair[1];
}
}
double ifelse_time = (clock() - start) * 1.0 / CLOCKS_PER_SEC;
start = clock();
for(auto pair: pairs){
result += (pair[0] > pair[1] ? pair[0] : pair[1]);
}
double op_time = (clock() - start) * 1.0 / CLOCKS_PER_SEC;
start = clock();
for(auto pair: pairs){
result += max(pair[0], pair[1]);
}
double libfunc_time = (clock() - start) * 1.0 / CLOCKS_PER_SEC;
cout << "ifelse cost: " << ifelse_time << endl;
cout << "?: cost: " << op_time << endl;
cout << "max() cost: " << libfunc_time << endl;
}
I generated 10,000,000 pairs (pair_num = 10,000,000). Here is the output: