C++中 直接调用、函数指针、std::function效率对比
C++中 直接调用、函数指针、std::function效率对比
调用次数:10亿次
CPU: i7 860 (主频2.8GHz)
测试结果: 函数指针要比直接调用慢2s左右;std::function 要比函数指针慢2s左右
貌似std::function调用时多了一句if语句的判断,用于测试是否绑定了函数。
结果及代码如下
/**@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;}