Advertisement
Guest User

Untitled

a guest
Sep 19th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. #include <iostream>
  2. #include <chrono>
  3. #include <memory>
  4. #include <functional>
  5.  
  6. using namespace std;
  7. using namespace std::chrono;
  8.  
  9. class Base
  10. {
  11. public:
  12. Base() {}
  13. virtual ~Base() {}
  14. virtual int func(int i) = 0;
  15. };
  16.  
  17. class Derived : public Base
  18. {
  19. public:
  20. Derived(int base = 10) : base{ base }
  21. {
  22.  
  23. }
  24. ~Derived() {}
  25.  
  26. virtual int func(int i)
  27. {
  28. return i * base;
  29. }
  30. private:
  31. int base;
  32. };
  33.  
  34. struct Func
  35. {
  36. int base;
  37. int operator()(int i)
  38. {
  39. return i * base;
  40. }
  41. Func(int base) : base{ base }
  42. {
  43.  
  44. }
  45. };
  46.  
  47. struct TestFunc
  48. {
  49. int base = 1;
  50.  
  51. int Call(int i)
  52. {
  53. return i * base;
  54. }
  55. };
  56. struct StdFunc
  57. {
  58. std::function<int(int)> m_Func;
  59. };
  60.  
  61. const int base = 10;
  62. int calculate(int i)
  63. {
  64. return base * i;
  65. }
  66.  
  67. int main()
  68. {
  69. const int num = 10000;
  70. Base* p = new Derived{ 10 };
  71. int total = 0;
  72. auto start = high_resolution_clock::now();
  73. for (int i = 0; i < num; ++i)
  74. {
  75. total += p->func(i);
  76. }
  77. auto end = high_resolution_clock::now();
  78. std::cout << "result: " << total << "\nvirtual call elapsed: \t" << duration_cast<nanoseconds>(end - start).count() << " nanoseconds.\n" << std::endl;
  79.  
  80. total = 0;
  81. start = high_resolution_clock::now();
  82. for (int i = 0; i < num; ++i)
  83. {
  84. total += calculate(i);
  85. }
  86. end = high_resolution_clock::now();
  87. std::cout << "result: " << total << "\ndirect function call elapsed: \t" << duration_cast<nanoseconds>(end - start).count() << " nanoseconds.\n" << std::endl;
  88.  
  89. Func functor{ 10 };
  90. total = 0;
  91. start = high_resolution_clock::now();
  92. for (int i = 0; i < num; ++i)
  93. {
  94. total += functor(i);
  95. }
  96. end = high_resolution_clock::now();
  97. std::cout << "result: " << total << "\nfunctor call elapsed: \t" << duration_cast<nanoseconds>(end - start).count() << " nanoseconds.\n" << std::endl;
  98.  
  99. int base = 10;
  100. function<int(int)> lambda = [base](int i)
  101. {
  102. return i * base;
  103. };
  104. total = 0;
  105. start = high_resolution_clock::now();
  106. for (int i = 0; i < num; ++i)
  107. {
  108. total += lambda(i);
  109. }
  110. end = high_resolution_clock::now();
  111. std::cout << "result: " << total << "\nlambda call elapsed: \t" << duration_cast<nanoseconds>(end - start).count() << " nanoseconds.\n" << std::endl;
  112. return 0;
  113. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement