在C++ 0x(在VS2010下)使用lambda表达式是否有任何开销?
我知道使用函数对象会产生开销,但我指的是传递给STL算法的表达式.编译器是否优化了表达式,消除了看起来像函数调用的东西?我开始非常喜欢lambda表达式,但我有点担心速度惩罚.
提前致谢!
我只是试图比较C++ 11中lambda表达式的性能,所以我做了测试 - 计算double值向量中元素的总和.这是实施:
#include <vector>
#include <algorithm>
#include <iostream>
#include <ctime>
#define LOG(x) { std::cout << #x << " = " << (x) << "\n"; }
#define TIME(t) { std::cout << ((double)(clock() - (t)) / CLOCKS_PER_SEC) << " s\n"; }
double sum(const std::vector<double>& v)
{
double s = 0.0;
for (auto i = v.cbegin(); i != v.cend(); ++i)
s += *i;
return s;
}
int main()
{
const size_t MAX = 1; // number of tests
const …Run Code Online (Sandbox Code Playgroud) 在多次调用时,为什么C++ lambda比普通函数慢?和C++ 0x Lambda开销 但我认为我的例子与前者的讨论有点不同,并且与后者的结果相矛盾.
在我的代码中搜索瓶颈时,我发现了一个recusive模板函数,它处理具有给定处理器函数的可变参数列表,比如将值复制到缓冲区中.
template <typename T>
void ProcessArguments(std::function<void(const T &)> process)
{}
template <typename T, typename HEAD, typename ... TAIL>
void ProcessArguments(std::function<void(const T &)> process, const HEAD &head, const TAIL &... tail)
{
process(head);
ProcessArguments(process, tail...);
}
Run Code Online (Sandbox Code Playgroud)
我将使用此代码的程序的运行时与lambda函数以及使用移动指针将参数复制到全局缓冲区的全局函数进行了比较:
int buffer[10];
int main(int argc, char **argv)
{
int *p = buffer;
for (unsigned long int i = 0; i < 10E6; ++i)
{
p = buffer;
ProcessArguments<int>([&p](const int &v) { *p++ = v; …Run Code Online (Sandbox Code Playgroud)