我使用 https://quick-bench.com/q/OdgFIOROlvUVzajZkaa5hemVupQ 对您的代码进行了基准测试
#include <iostream>
class Addition1{
public:
int sum (int a, int b){
return a+b;
}
double sum (double a, double b){
return a+b;
}
};
template <class T>
class Addition2{
public:
T sum(T a,T b){
return a+b;
}
};
static void Overloading(benchmark::State& state) {
// Code inside this loop is measured repeatedly
for (auto _ : state) {
Addition1 a;
std::cout<<a.sum(5,6)<<std::endl;
std::cout<<a.sum(5.1,6.2)<<std::endl;
benchmark::DoNotOptimize(a);
}
}
// Register the function as a benchmark
BENCHMARK(Overloading);
static void Generic(benchmark::State& state) {
// Code before the loop is not measured
for (auto _ : state) {
Addition2 <int>a;
Addition2 <double>b;
std::cout<<a.sum(5,6)<<std::endl;
std::cout<<b.sum(5.1,6.2);
benchmark::DoNotOptimize(a);
benchmark::DoNotOptimize(b);
}
}
BENCHMARK(Generic);
不同之处在于您的第二个代码中缺少 <<endl。
在我添加它之后,基准是相等的:https://quick-bench.com/q/vCxh4G8acvEAR2IWisU-gFbZdE0
#include <iostream>
class Addition1{
public:
int sum (int a, int b){
return a+b;
}
double sum (double a, double b){
return a+b;
}
};
template <class T>
class Addition2{
public:
T sum(T a,T b){
return a+b;
}
};
static void Overloading(benchmark::State& state) {
// Code inside this loop is measured repeatedly
for (auto _ : state) {
Addition1 a;
std::cout<<a.sum(5,6)<<std::endl;
std::cout<<a.sum(5.1,6.2)<<std::endl;
benchmark::DoNotOptimize(a);
}
}
// Register the function as a benchmark
BENCHMARK(Overloading);
static void Generic(benchmark::State& state) {
// Code before the loop is not measured
for (auto _ : state) {
Addition2 <int>a;
Addition2 <double>b;
std::cout<<a.sum(5,6)<<std::endl;
std::cout<<b.sum(5.1,6.2)<<std::endl;
benchmark::DoNotOptimize(a);
benchmark::DoNotOptimize(b);
}
}
BENCHMARK(Generic);
将endl 替换为'\n' 会稍微提高性能:
https://quick-bench.com/q/GsNKlf5k2ZK3r8n6RHy68USWvdg
#include <iostream>
class Addition1{
public:
int sum (int a, int b){
return a+b;
}
double sum (double a, double b){
return a+b;
}
};
template <class T>
class Addition2{
public:
T sum(T a,T b){
return a+b;
}
};
static void Overloading(benchmark::State& state) {
// Code inside this loop is measured repeatedly
for (auto _ : state) {
Addition1 a;
std::cout<<a.sum(5,6)<<'\n';
std::cout<<a.sum(5.1,6.2)<<'\n';
benchmark::DoNotOptimize(a);
}
}
// Register the function as a benchmark
BENCHMARK(Overloading);
static void OverloadingEndl(benchmark::State& state) {
// Code inside this loop is measured repeatedly
for (auto _ : state) {
Addition1 a;
std::cout<<a.sum(5,6)<<std::endl;
std::cout<<a.sum(5.1,6.2)<<std::endl;
benchmark::DoNotOptimize(a);
}
}
// Register the function as a benchmark
BENCHMARK(OverloadingEndl);