Guest User

Untitled

a guest
Jun 25th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.63 KB | None | 0 0
  1.  
  2. #include <vector>
  3. #include <iostream>
  4. #include <chrono>
  5.  
  6.  
  7. void bench(size_t iterations, std::function<void ()> func)
  8. {
  9.  
  10.     using namespace std::chrono;
  11.    
  12.     auto start = high_resolution_clock::now();
  13.     for(size_t i = 0; i < iterations; ++i)
  14.     {
  15.         func();
  16.     }
  17.     auto stop = high_resolution_clock::now();
  18.    
  19.     nanoseconds duration = stop - start;
  20.    
  21.     std::cout << "Ran " << iterations << " iterations, which took " <<
  22.               duration.count() << "ns" << std::endl;
  23.  
  24.     if(iterations>1)
  25.     {
  26.         std::cout << "Which is " << duration.count()/iterations << "ns per iteration " << std::endl;
  27.     }
  28.    
  29. }
  30.  
  31. class range {
  32.     int b, e;
  33. public:
  34.    
  35.     class iterator
  36.     {
  37.         int value;
  38.     public:
  39.         iterator(int v) : value(v) {}
  40.         bool operator==(const iterator& other) const { return value == other.value; }
  41.         bool operator!=(const iterator& other) const { return value != other.value; }
  42.         const iterator& operator++() { value++; return *this; }
  43.         const iterator& operator--() { value--; return *this; }
  44.         int operator*() const { return value; }
  45.     };
  46.    
  47.     range(int b_, int e_) : b(b_), e(e_) {}
  48.     iterator begin() { return b; }
  49.     iterator end() { return e+1; }
  50. };
  51.  
  52. int main()
  53. {
  54.  
  55.     int ITER = 10000;
  56.  
  57.     bench(ITER, [](){
  58.  
  59.         int sum = 0;
  60.         for( auto i : range(1,1000) )
  61.         {
  62.             sum += i;
  63.         }
  64.  
  65.         });
  66.  
  67.     bench(ITER, [](){
  68.  
  69.         int sum = 0;
  70.         for(int i = 1; i < 1000; ++i)
  71.         {
  72.             sum += i;
  73.         }
  74.  
  75.         });
  76.  
  77.  
  78.  
  79.     return 0;
  80. }
Add Comment
Please, Sign In to add comment