fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <chrono>
  4. #include <cmath>
  5.  
  6. using namespace std;
  7. using namespace chrono;
  8.  
  9. class Stat
  10. {
  11. public:
  12. Stat():x(0),x2(0),n(0){}
  13. void add(double y) { x += y; x2 += y*y; n++; }
  14.  
  15. pair<double,double> get() const
  16. {
  17. pair<double,double> p;
  18. p.first = x/n;
  19. p.second = sqrt((n*x2-x*x)/n/(n-1));
  20. return p;
  21. }
  22. private:
  23. double x, x2;
  24. int n;
  25. };
  26.  
  27. class Experiment
  28. {
  29. public:
  30. Experiment(void (*f)(int), int cnt, int n)
  31. :f(f),cnt(cnt),n(n)
  32. {
  33. }
  34. pair<double,double> doit();
  35. private:
  36. void (*f)(int);
  37. int cnt, n;
  38. };
  39.  
  40.  
  41. pair<double,double> Experiment::doit()
  42. {
  43. using Clock = high_resolution_clock;
  44. Stat st;
  45. for(int i = 0; i < cnt; ++i)
  46. {
  47. Clock::time_point start_ = Clock::now();
  48. f(n);
  49. Clock::time_point stop_ = Clock::now();
  50. Clock::duration dt = stop_ - start_;
  51. st.add(static_cast<double>(duration_cast<microseconds>(dt).count()));
  52. }
  53. return st.get();
  54. }
  55.  
  56. int sum = 0; // Просто чтоб оптимизатор не выбросил...
  57.  
  58. void foo(int n)
  59. {
  60. int s = 0;
  61. for(int i = 0; i < n; ++i)
  62. for(int j = 0; j < n; ++j)
  63. s += i*j;
  64. sum += s;
  65. }
  66.  
  67. int main()
  68. {
  69.  
  70. for(int n = 100; n < 1000; n+= 100)
  71. {
  72. Experiment ex(foo,
  73. 5, // Число повторов
  74. n);
  75. auto p = ex.doit();
  76.  
  77. cout << " N = " << fixed << setw(7) << n <<
  78. " time = " << fixed << setprecision(1) << setw(12) << p.first
  79. << " +- " << p.second << " mks\n";
  80. }
  81. cout << sum;
  82. }
  83.  
  84.  
Success #stdin #stdout 0.02s 4648KB
stdin
Standard input is empty
stdout
 N =     100   time =           6.4 +- 0.5 mks
 N =     200   time =          30.2 +- 1.5 mks
 N =     300   time =          77.0 +- 6.0 mks
 N =     400   time =         128.2 +- 4.4 mks
 N =     500   time =         199.0 +- 13.8 mks
 N =     600   time =         256.4 +- 15.5 mks
 N =     700   time =         370.2 +- 9.1 mks
 N =     800   time =         487.8 +- 39.4 mks
 N =     900   time =         672.8 +- 23.3 mks
305615780