Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <chrono>
- #include <memory>
- #include <functional>
- using namespace std;
- using namespace std::chrono;
- class Base
- {
- public:
- Base() {}
- virtual ~Base() {}
- virtual int func(int i) = 0;
- };
- class Derived : public Base
- {
- public:
- Derived(int base = 10) : base{ base }
- {
- }
- ~Derived() {}
- virtual int func(int i)
- {
- return i * base;
- }
- private:
- int base;
- };
- struct Func
- {
- int base;
- int operator()(int i)
- {
- return i * base;
- }
- Func(int base) : base{ base }
- {
- }
- };
- struct TestFunc
- {
- int base = 1;
- int Call(int i)
- {
- return i * base;
- }
- };
- struct StdFunc
- {
- std::function<int(int)> m_Func;
- };
- const int base = 10;
- int calculate(int i)
- {
- return base * i;
- }
- int main()
- {
- const int num = 10000;
- Base* p = new Derived{ 10 };
- int total = 0;
- auto start = high_resolution_clock::now();
- for (int i = 0; i < num; ++i)
- {
- total += p->func(i);
- }
- auto end = high_resolution_clock::now();
- std::cout << "result: " << total << "\nvirtual call elapsed: \t" << duration_cast<nanoseconds>(end - start).count() << " nanoseconds.\n" << std::endl;
- total = 0;
- start = high_resolution_clock::now();
- for (int i = 0; i < num; ++i)
- {
- total += calculate(i);
- }
- end = high_resolution_clock::now();
- std::cout << "result: " << total << "\ndirect function call elapsed: \t" << duration_cast<nanoseconds>(end - start).count() << " nanoseconds.\n" << std::endl;
- Func functor{ 10 };
- total = 0;
- start = high_resolution_clock::now();
- for (int i = 0; i < num; ++i)
- {
- total += functor(i);
- }
- end = high_resolution_clock::now();
- std::cout << "result: " << total << "\nfunctor call elapsed: \t" << duration_cast<nanoseconds>(end - start).count() << " nanoseconds.\n" << std::endl;
- int base = 10;
- function<int(int)> lambda = [base](int i)
- {
- return i * base;
- };
- total = 0;
- start = high_resolution_clock::now();
- for (int i = 0; i < num; ++i)
- {
- total += lambda(i);
- }
- end = high_resolution_clock::now();
- std::cout << "result: " << total << "\nlambda call elapsed: \t" << duration_cast<nanoseconds>(end - start).count() << " nanoseconds.\n" << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement