为什么C ++ lambda在调用多次时比普通函数慢? [英] Why C++ lambda is slower than ordinary function when called multiple times?

查看:171
本文介绍了为什么C ++ lambda在调用多次时比普通函数慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是试图比较C ++ 11中lambda表达式的性能,所以我做了一个测试 - 计算元素的向量中的 double 值。下面是实现:

I just have tried to compare performance of lambda expressions in C++11, so I did the test -- compute sum of elements in a vector of double values. Here is the implementation:

#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 size_t SIZE = 100000000; // length of the vector

    std::vector<double> v(SIZE, 1.0);
    double out;

    clock_t clk;

    std::cout << "iterator\n";

    clk = clock();
    out = 0.0;
    for (size_t i = 0; i < MAX; ++i)
        out += sum(v);
    TIME(clk)
    LOG(out)

    std::cout << "\nlambda\n";

    clk = clock();
    out = 0.0;
    for (size_t i = 0; i < MAX; ++i)
        std::for_each(v.cbegin(), v.cend(), [&](double d) { out += d; });
    TIME(clk)
    LOG(out)

    return 0;
}

这是程序的结果(编译在VS2010 SP1中, ):

Here is the result of this program (compiled in VS2010 SP1, in Release mode):


iterator
0.32 s
out = 1e+008

lambda
0.326 s
out = 1e+008

可以看到,性能几乎没有差别。但是,如果我给出10作为 MAX 的值(这意味着求和将执行10次,而不是一次),结果不同:

As one may see, there is practically no difference in performance. However, if I give 10 as the value of MAX (it means summation will be performed 10 times instead of one), results differ:


iterator
0.287 s
out = 1e+009

lambda
2.84 s
out = 1e+009

测试lambda表达式大约需要10倍的时间。为什么?我认为这可能是由每个迭代创建新的lambda,但是我尝试这样的事实:

Test for lambda expression took approximately 10 times more time. Why? I thought it may be caused by the fact, that on every iteration new lambda is created, but whet I tried this:

out = 0.0;
auto f = [&](double d) { out += d; };
for (size_t i = 0; i < MAX; ++i)
    std::for_each(v.cbegin(), v.cend(), f);

结果未更改。

推荐答案

原来,这不是lambda表达式的任何问题,只是编译器通过缓存 sum()函数的结果优化了第一种情况下的外层循环。将第一种情况更改为此形式后:

It turned out, that this is not any issue with lambda expressions, just the compiler optimized-out the outer loop in the first case by caching the result of the sum() function. After change the first case to this form:

out = 0.0;
for (size_t i = 0; i < MAX; ++i)
{
    out += sum(v);
    v[i] = 1.0; // this adds O(1) time and prevents caching
}

大约相等,用lambda作为收藏。

both cases timings are approximately equal, with lambda as a favourite.

这篇关于为什么C ++ lambda在调用多次时比普通函数慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆