During runtime, given a number N (unsigned long int), I have to take 2*N inputs from the user. I have to store them. The task is done and the question is not about how to do it. I was experimenting with the code and how to make it more standard and efficient. So, there are following three options among others :
- Construct two
std::vector<unsigned long int>
vectors, to store first and second element respectively of each pair. -
Construct one
std::vector<unsigned long int>
vector of length 2*N. -
Construct one
std::vector<std::pair<unsigned long int, unsigned long int> >
.
So, I wrote this little program to see the execution speeds.
#include<iostream>
#include<vector>
#include<utility>
#include<ctime>
using namespace std;
int main(int argc, char* argv[]){
const unsigned long int len{10};
clock_t time1{clock()};
vector<unsigned long int>veca(2*len);
// vector<unsigned long int>vecb(len);
cout<<(double)(clock()-time1)/CLOCKS_PER_SEC<<endl;
time1 = clock();
typedef pair<unsigned long int, unsigned long int> NumberPair;
vector<NumberPair>vecu(len);
cout<<(double)(clock()-time1)/CLOCKS_PER_SEC<<endl;
return 1;
}
The output was
- 6.8e-05
- 2e-06
If instead of 10, a length of 10^10 is used, then, the output is
- 2e-06
- 1e-06
Thus it is better to go for choice 3 than choice 2.
Similarly by changing the code, it can be shown that choice 3 is better than choice 1.
Moreover the change in execution times, is lesser for large data sizes (execution time halves in case of option 3 !!!), and more for small data sizes (almost 32 to 38 times).
What is the explanation of such a behavior ?
Aucun commentaire:
Enregistrer un commentaire