Advertisement
bogolyubskiyalexey

speed test for insert to begin

Nov 11th, 2017
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.79 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.     m.reserve(2*count);
  49.    
  50.     double start = clock();
  51.    
  52.     for (int i = 0; i < count; ++i) {
  53.         m.insert(m.begin(), values[i]);
  54.     }
  55.    
  56.     double end = clock();
  57.     return (end - start) / CLOCKS_PER_SEC;
  58. }
  59.  
  60.  
  61.  
  62. int main() {
  63.     vector<int> counts = {
  64.          10000,
  65.          50000,
  66.         100000,
  67.         500000,
  68.        1000000,
  69.        5000000
  70.     };
  71.     int max_count = counts.back();
  72.     int* v = new int[max_count];
  73.     for (int i = 0; i < max_count; ++i) {
  74.         v[i] = rand();
  75.     }
  76.     vector<function<double(int, int[])>> tests = {
  77.         test0,
  78.         test1,
  79.         test2
  80.     };
  81.  
  82.     for (auto count : counts) {
  83.         printf("count=%d\n", count);
  84.         for (int i = 0; i < tests.size(); ++i) {
  85.             printf("\ttest #%d\t: \t%.10lfsec\n", i, tests[i](count, v));
  86.         }
  87.     }
  88.     return 0;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement