fork(1) download
  1. #include <iostream>
  2. #include <vector>
  3. #include <cstdlib>
  4. #include <chrono>
  5.  
  6. using namespace std;
  7.  
  8. struct base
  9. {
  10. int type;
  11. virtual ~base() {}
  12. };
  13.  
  14. struct class1 : base
  15. {
  16. class1() { type = 1; }
  17. int get() { return 11; }
  18. };
  19.  
  20. struct class2 : public base
  21. {
  22. class2() { type = 2; }
  23. int get() { return 27; }
  24. };
  25.  
  26. class timer
  27. {
  28. using T = std::chrono::time_point<std::chrono::steady_clock>;
  29. T t1, t2;
  30. public:
  31. void start() { t1 = std::chrono::steady_clock::now(); }
  32. void stop() { t2 = std::chrono::steady_clock::now(); }
  33. void print() const { std::cout << "Time: " << (t2 - t1).count() << endl; }
  34. };
  35.  
  36. int main()
  37. {
  38. vector <base *> v;
  39. int s = 0;
  40. timer t;
  41.  
  42. srand(time(0));
  43. for (unsigned q=0; q<50000000; ++q) v.push_back(rand()&1 ? (base*)new class1() : (base*)new class2());
  44.  
  45. t.start();
  46. for (auto x : v)
  47. switch (x->type)
  48. {
  49. case 1: s += ((class1*)x)->get(); break;
  50. case 2: s += ((class2*)x)->get(); break;
  51. }
  52. t.stop();
  53.  
  54. cout << s << endl;
  55. t.print();
  56.  
  57. for (auto x : v) delete x;
  58.  
  59. return 0;
  60. }
Success #stdin #stdout 3.34s 1577472KB
stdin
Standard input is empty
stdout
949948464
Time: 245933290