Advertisement
bogolyubskiyalexey

speed test for insert to end element

Nov 11th, 2017
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <functional>
  4. #include <cstring>
  5.  
  6.  
  7. using namespace std;
  8.  
  9.  
  10. double test0(int count, int values[]) {
  11.     int* m = new int[count];
  12.    
  13.     double start = clock();
  14.    
  15.     for (int i = 0; i < count; ++i) {
  16.         for (int j = 0; j < i; ++j) {
  17.             m[j + 1] = m[j];
  18.         }
  19.         m[0] = values[i];
  20.     }
  21.    
  22.     double end = clock();
  23.     delete m;
  24.     return (end - start) / CLOCKS_PER_SEC;
  25. }
  26.  
  27. double test1(int count, int values[]) {
  28.     int* m = new int[count];
  29.    
  30.     double start = clock();
  31.    
  32.     int bytes = sizeof(m[0]);
  33.     int bytesInArray = 0;
  34.    
  35.     for (int i = 0; i < count; ++i) {
  36.         memmove(m + 1, m, bytesInArray);
  37.         m[0] = values[i];
  38.         bytesInArray += bytes;
  39.     }
  40.    
  41.     double end = clock();
  42.     delete m;
  43.     return (end - start) / CLOCKS_PER_SEC;
  44. }
  45.  
  46. double test2(int count, int values[]) {
  47.     vector<int> m;
  48.    
  49.     double start = clock();
  50.    
  51.     for (int i = 0; i < count; ++i) {
  52.         m.push_back(values[i]);
  53.     }
  54.    
  55.     double end = clock();
  56.     return (end - start) / CLOCKS_PER_SEC;
  57. }
  58.  
  59.  
  60.  
  61. int main() {
  62.     vector<int> counts = {
  63.          10000,
  64.          50000,
  65.         100000,
  66.         500000,
  67.        1000000,
  68.        5000000
  69.     };
  70.     int max_count = counts.back();
  71.     int* v = new int[max_count];
  72.     for (int i = 0; i < max_count; ++i) {
  73.         v[i] = rand();
  74.     }
  75.     vector<function<double(int, int[])>> tests = {
  76.         test0,
  77.         test1,
  78.         test2
  79.     };
  80.  
  81.     for (auto count : counts) {
  82.         printf("count=%d\n", count);
  83.         for (int i = 0; i < tests.size(); ++i) {
  84.             printf("\ttest #%d\t: \t%.10lfsec\n", i, tests[i](count, v));
  85.         }
  86.     }
  87.     return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement