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; }
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
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
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);
the results hadn't changed. Could someone explain that behaviour to me?
Being anonymous, lambda functions can be easily passed without being assigned to a variable. Lambda functions are inline functions and thus execute comparatively faster.
The answer is it depends. I have seen cases where using a lambda was slower and where it was faster. I have also seen that with newer updates you get more optimal code.
sorting - Why is a C++ Lambda function much faster as compare function than an equivalent object - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.
You can use a lambda function that you don't even have to assign to a variable, you can invoke it immediately, hence it's called the immediately invoked lambda function.
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 }
both cases timings are approximately equal, with lambda as a favourite.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With