C++中 直接调用、函数指针、std::function效率对比

[size=large]C++中 直接调用、函数指针、std::function效率对比

调用次数:10亿次
CPU: i7 860 (主频2.8GHz)
[color=red]测试结果:[/color] 函数指针要比直接调用慢2s左右;std::function 要比函数指针慢2s左右

貌似std::function调用时多了一句if语句的判断,用于测试是否绑定了函数。

结果及代码如下[/size]

[img]http://dl2.iteye.com/upload/attachment/0092/9910/1f4484ae-3d01-31b7-88dc-20dd15c32a10.png[/img]

[img]http://dl2.iteye.com/upload/attachment/0092/9912/901faa72-afc6-3a4f-b7a9-708186c39f44.png[/img]

/**
@file
@brief 测试C++11 中 function的效率
*/


#include <functional>
#include <iostream>
#include <typeinfo>
#include <chrono>

//待封装的函数
int testEfficiency (int i, int j) {
for (size_t ii = 0; ii < 5; ii++) {
i += i - ii;
}
if (i < j)
return i + 7 * j;
else return i - 3 * j;
}

typedef std::function<int (int, int) > FuncInt_IntInt;
using funcInt_IntInt = int (*) (int, int); //函数指针

int main() {
int a = 1;
int b = a;
int c = a;
int testNum = 1E9;
FuncInt_IntInt fFunctional = testEfficiency;
funcInt_IntInt fFuncPtr = testEfficiency;

std::cout << "函数原型类型:\t\t" << typeid (testEfficiency).name() << std::endl;
std::cout << "std::funciton类型:\t" << typeid (fFunctional).name() << std::endl;
std::cout << "函数指针类型:\t\t" << typeid (fFuncPtr).name() << std::endl;


std::chrono::time_point<std::chrono::system_clock> start, end;

start = std::chrono::system_clock::now();
for (size_t i = 0; i < testNum; i++) {
a = testEfficiency (a, 2);
}
end = std::chrono::system_clock::now();
std::cout << "直接调用耗时:\t\t" << std::chrono::duration<double> (end - start).count() << "秒" << std::endl;

start = std::chrono::system_clock::now();
for (size_t i = 0; i < testNum; i++) {
b = fFunctional (b, 2);
}
end = std::chrono::system_clock::now();
std::cout << "使用std::function耗时:\t" << std::chrono::duration<double> (end - start).count() << "秒" << std::endl;

start = std::chrono::system_clock::now();
for (size_t i = 0; i < testNum; i++) {
c = fFuncPtr (c, 2);
}
end = std::chrono::system_clock::now();
std::cout << "使用函数指针耗时:\t" << std::chrono::duration<double> (end - start).count() << "秒" << std::endl;

std::cout << "a=" << a << std::endl;
std::cout << "b=" << b << std::endl;
std::cout << "c=" << c << std::endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值