Skip to content

Instantly share code, notes, and snippets.

@jacking75
Forked from benloong/functionperformance.cpp
Last active September 17, 2019 01:24
Show Gist options
  • Save jacking75/5d24a80f5dbdde615a1d6aabf81f6434 to your computer and use it in GitHub Desktop.
Save jacking75/5d24a80f5dbdde615a1d6aabf81f6434 to your computer and use it in GitHub Desktop.
c++11 direct function call, virtual function call, functor and std::function(using a lambda) performance test
#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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment