C/C++教程

C++中函数指针、lamada表达式、bind间的效率对比

本文主要是介绍C++中函数指针、lamada表达式、bind间的效率对比,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

由于工作需要,写了一个Demo来测试C++中原始的函数指针、lamada、bind之间的性能。代码如下:

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

auto res = 0;

long test_func(long i)
{
	return i;
}


auto test_lambda = [](int i)
{
	test_func(i);
};


auto test_bind = std::bind(test_func, std::placeholders::_1);

auto test_func_ptr = test_func;

std::function<void(int)> test_bind_lambda = test_lambda;
int main()
{
	auto times = 10000000000LL;

	auto t0 = std::chrono::high_resolution_clock::now();
	for (auto i = 0LL; i < times; i++)
		test_lambda(i);
	auto t1 = std::chrono::high_resolution_clock::now();


	for (auto i = 0LL; i < times; i++)
		test_bind(i);
	auto t2 = std::chrono::high_resolution_clock::now();


	for (auto i = 0LL; i < times; i++)
		test_func_ptr(i);
	auto t3 = std::chrono::high_resolution_clock::now();
	for (auto i = 0LL; i < times; i++)
		test_bind_lambda(i);
	auto t4 = std::chrono::high_resolution_clock::now();

	std::cout << "lambda: " << std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count() << std::endl;
	std::cout << "bind: " << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count() << std::endl;
	std::cout << "func_ptr: " << std::chrono::duration_cast<std::chrono::milliseconds>(t3 - t2).count() << std::endl;
	std::cout << "bind_lambda: " << std::chrono::duration_cast<std::chrono::milliseconds>(t4 - t3).count() << std::endl;

	system("pause");
	return 0;
}

第一次跑的结果如下:

但是 如果认真想想,lamda和func_ptr再怎么优秀,也不会运行时间为0呀。之所以是这样的结果是因为Demo中的函数都过于简单,而VS默认会开编译优化。Demo中的lamda和func_ptr被优化后实际上是被优化没了。所以时间为0。

关闭编译优化后再次运行,结果如下:

可见bind比lamda和func_ptr慢了一个数量级 

总结:虽然bind在运行上会有效率损失,但是用得好了会提高编码效率。不必因为它的性能损失而嫌弃它,在实际应用中几乎是可以忽略不计的。

这篇关于C++中函数指针、lamada表达式、bind间的效率对比的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!