Aucune description

insert.cpp 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Compare the execution times of inserting at the front vs. inserting
  2. // at the back of a vector.
  3. //
  4. // Usage:
  5. // ./<exec name> <size of list>
  6. #include <iostream>
  7. #include <vector>
  8. #include <cstdlib>
  9. #include <algorithm>
  10. using namespace std;
  11. void insertManyFront(vector<int> & v, int size) {
  12. for (int i = 0; i < size; i++)
  13. v.insert(v.begin(), rand() % size);
  14. }
  15. void insertManyBack(vector<int> & v, int size) {
  16. for (int i = 0; i < size; i++)
  17. v.push_back(rand() % size);
  18. }
  19. int main(int argc, char *argv[]) {
  20. if (argc < 2) {
  21. cout << "Usage: " << argv[0] << " <size> \n";
  22. exit(1);
  23. }
  24. int size = atoi(argv[1]);
  25. vector<int> v,w;
  26. // initialize the random seed
  27. srand(time(NULL));
  28. double elapsed_secs;
  29. // measure time to insert many elements in front
  30. clock_t begin = clock();
  31. insertManyFront(v, size);
  32. clock_t end = clock();
  33. elapsed_secs = static_cast<double>(end - begin) / CLOCKS_PER_SEC;
  34. cout << "\nInsert at front elapsed: " << elapsed_secs << " seconds\n";
  35. // measure time to insert many elements in the back
  36. begin = clock();
  37. insertManyBack(w, size);
  38. end = clock();
  39. elapsed_secs = static_cast<double>(end - begin) / CLOCKS_PER_SEC;
  40. cout << "Insert back elapsed: " << elapsed_secs << " seconds\n\n";
  41. return 0;
  42. }