Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <chrono>
- #include <functional>
- using namespace std;
- using namespace std::chrono;
- class Base
- {
- public:
- Base(){}
- virtual ~Base(){}
- virtual int func(int i) volatile = 0;
- };
- class Derived : public Base
- {
- public:
- Derived(int base = 10) : base{base}
- {
- }
- ~Derived(){}
- virtual int func(int i) volatile
- {
- return i*base;
- }
- private:
- int base;
- };
- struct Func
- {
- int base;
- int __attribute__ ((noinline)) operator()(int i)
- {
- return i*base;
- }
- Func(int base) : base {base}
- {
- }
- };
- const int base = 10;
- int __attribute__ ((noinline)) calculate(int i)
- {
- return base*i;
- }
- int main()
- {
- const int num = 6000;
- volatile 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;
- function<int(int, int)> lambda1 = [](int i, int base)
- {
- return i * base;
- };
- total = 0;
- start = high_resolution_clock::now();
- for (int i = 0; i < num; ++i)
- {
- total += lambda1(i, base);
- }
- end = high_resolution_clock::now();
- std::cout<<"result: "<<total<<"\nlambda1 call elapsed: \t"<<duration_cast<nanoseconds>(end-start).count()<<" nanoseconds.\n"<<std::endl;
- const int base = 10;
- function<int(int)> lambda2 = [base](int i)
- {
- return i*base;
- };
- total = 0;
- start = high_resolution_clock::now();
- for (int i = 0; i < num; ++i)
- {
- total += lambda2(i);
- }
- end = high_resolution_clock::now();
- std::cout<<"result: "<<total<<"\nlambda2 call elapsed: \t"<<duration_cast<nanoseconds>(end-start).count()<<" nanoseconds.\n"<<std::endl;
- function<int(int)> bound = std::bind(calculate, std::placeholders::_1);
- total = 0;
- start = high_resolution_clock::now();
- for (int i = 0; i < num; ++i)
- {
- total += bound(i);
- }
- end = high_resolution_clock::now();
- std::cout<<"result: "<<total<<"\nbound 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