#include <iostream>
#include <functional>
#include <benchmark/benchmark.h>
class Calculator {
public:
virtual int calculate(int x, int y) = 0;
};
class Minus : public Calculator {
public:
virtual int calculate(int x, int y) override {
return x + y;
}
};
class Plus : public Calculator {
public:
virtual int calculate(int x, int y) override {
return x - y;
}
};
class CalculatorClient {
public:
CalculatorClient(Calculator *p) : client_(p) {
}
public:
int calculate(int x, int y) {
return client_->calculate(x, y);
}
private:
Calculator *client_ = nullptr;
};
class BindCalculatorClient {
public:
BindCalculatorClient(std::function<int(int, int)>&&func) : func_(std::move(func)) {
}
public:
int calculate(int x, int y) {
return func_(x, y);
}
private:
std::function<int(int, int)>func_;
};

static void BM_TestVirtualFunction(benchmark::State &state) {
Minus minus;
CalculatorClient client0(&minus);

Plus plus;
CalculatorClient client1(&plus);

for (auto _ : state) {
client0.calculate(1, 2);
client1.calculate(1, 2);
}
}
static void BM_TestBindFunction(benchmark::State &state) {
Minus minus;
BindCalculatorClient client0(std::bind(&Minus::calculate, minus, std::placeholders::_1, std::placeholders::_2));

Plus plus;
BindCalculatorClient client1(std::bind(&Plus::calculate, plus, std::placeholders::_1, std::placeholders::_2));

for (auto _ : state) {
client0.calculate(1, 2);
client1.calculate(1, 2);
}
}

BENCHMARK(BM_TestVirtualFunction)->Iterations(100000000);
BENCHMARK(BM_TestBindFunction)->Iterations(100000000);
BENCHMARK_MAIN();

虚函数与bind对比测试_#include