简体   繁体   English

为什么 C++ 模板代码在我的 lambda 表达式中运行得更快?

[英]Why C++ template code runs faster in my lambdas?

I've been doing some simple vector data accumulate tests and wondering why the following code:我一直在做一些简单的矢量数据累积测试,想知道为什么会出现以下代码:

template<typename T>
T accum(typename vector<T>::const_iterator first, typename vector<T>::const_iterator last, T init) {
  for(; first != last; ++first)
    init += *first;
  return init;
}

runs faster than the following code (both in lamda) ?运行速度比以下代码(均在 lamda 中)快?

test("Iterator/direct", table, [](auto& values) {
  auto sum {0.0};
  for(auto i = values.begin(); i != values.end(); ++i)
    sum += *i;
  return(sum);
});

In my eyes the algorithm itself should be quite much the same.在我看来,算法本身应该大同小异。

The whole source code (53 lines) can be found in this Gist .整个源代码(53 行)可以在这个 Gist 中找到。

Compile with -O2 option and the execution times will be practically negligible.使用 -O2 选项编译,执行时间几乎可以忽略不计。 Thank you very much for all commenters.非常感谢所有评论者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在这种情况下,我的 Java 代码比我的 C++ 代码运行得快? - Why in this case, my Java code runs faster than my C++ code? 为什么我的程序在1个线程上比在8个线程上运行更快? - Why my program runs faster on 1 thread than on 8. C++ 为什么我的SSE不比C / C ++代码快? - why is my SSE not faster than C/C++ code? 为什么这个C ++代码没有更快? - Why this c++ code is not faster? 为什么我的 Python NumPy 代码比 C++ 快? - Why is my Python NumPy code faster than C++? 为什么我的 C++14 KosaRaju 算法在类似的编写代码运行得更快时得到 TLE - Why my C++14 KosaRaju algo getting TLE when a similar written code runs much faster c ++ vs MATLAB优化以提高速度。 例如我的matlab代码比c ++运行得快? - c++ vs MATLAB optimization for speed. E.g. my matlab code runs faster than c++? 如果我在代码块中构建代码,为什么我的代码运行得更快? - Why my code runs faster if I build it in codeblocks? 为什么我查找素数的 D 代码比我的 C++ 代码快得多? - Why is my D code for finding prime numbers much faster than my C++ code? C ++代码缺少标头运行,为什么? - C++ code runs with missing header, why?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM