传递给std :: sort时,全局函数比functor或lambda慢

Ale*_*x F 6 c++ optimization lambda functor c++11

我做了一个小测试来检查全局函数/ functor/lambda的性能作为函数的比较器参数std::sort.Functor和lambda具有相同的性能.我惊讶地发现,看起来最简单的回调的全局函数要慢得多.

#include <stdafx.h>
#include <windows.h>
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;

const int vector_size = 100000;

bool CompareFunction(const string& s1, const string& s2) 
{ 
    return s1[0] < s2[0];  // I know that is crashes on empty string, but this is not the point here
}

struct CompareFunctor 
{
    bool operator() (const string& s1, const string& s2) 
    { 
        return s1[0] < s2[0]; 
    }
} compareFunctor;

int main()
{
    srand ((unsigned int)time(NULL));
    vector<string> v(vector_size);

    for(size_t i = 0; i < vector_size; ++i)
    {
        ostringstream s;
        s << rand();
        v[i] = s.str().c_str();
    }

    LARGE_INTEGER freq;
    LARGE_INTEGER beginTime, endTime;
    QueryPerformanceFrequency(&freq);
    QueryPerformanceCounter(&beginTime);

    // One of three following lines should be uncommented
    sort(v.begin(), v.end(), CompareFunction);
    // sort(v.begin(), v.end(), compareFunctor);
    // sort(v.begin(), v.end(), [](const string& s1, const string& s2){return s1[0] < s2[0];});

    QueryPerformanceCounter(&endTime);
    float f = (endTime.QuadPart - beginTime.QuadPart) *  1000.0f/freq.QuadPart;      // time in ms
    cout << f << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

一些Windows特定的代码用于精确的执行时间测量.环境:Windows 7,Visual C++ 2010.当然,打开默认优化的发布配置.执行时间处理时间:

Global function 2.6 - 3.6 ms   (???)
Functor - 1.7 - 2.4 ms
Lambda - 1.7 - 2.4 ms
Run Code Online (Sandbox Code Playgroud)

那么,为什么全局函数更慢?VC++编译器有什么问题,还是别的什么?

von*_*and 0

您应该调用该排序数千次才能获得更精确的结果。

速度有多快取决于编译器的智能。它可能会内联一些操作(很可能是 lambda,可能是函子,不太可能是非内联全局变量)。另外,比较是否内联将取决于其复杂性;结果会有所不同。

我强烈建议不要考虑如此详细的“优化”。您的编程时间比您在运行时获得的(非常小的)收益要昂贵得多专注于编写干净、易懂、简单的代码。下周试图理解“为终极速度而苦恼”的代码只会让你过早地秃头。