相关疑难解决方法(0)

qsort vs std :: sort的表现?

根据Scott Meyers的说法,在他的Effective STL书中 - 第46项.他声称这std::sort比std::qsort内联的事实要快670%.我测试了自己,我看到qsort更快:(!有谁可以帮我解释这个奇怪的行为?

#include <iostream>
#include <vector>
#include <algorithm>

#include <cstdlib>
#include <ctime>
#include <cstdio>

const size_t LARGE_SIZE = 100000;

struct rnd {
    int operator()() {
        return rand() % LARGE_SIZE;
    }
};

int comp( const void* a, const void* b ) {
    return ( *( int* )a - *( int* )b );
}

int main() {
    int ary[LARGE_SIZE];
    int ary_copy[LARGE_SIZE];
    // generate random data
    std::generate( ary, ary + LARGE_SIZE, rnd() );
    std::copy( ary, ary …
Run Code Online (Sandbox Code Playgroud)

c++ sorting performance stl

70
推荐指数
6
解决办法
6万
查看次数

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

我做了一个小测试来检查全局函数/ 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() …
Run Code Online (Sandbox Code Playgroud)

c++ optimization lambda functor c++11

6
推荐指数
1
解决办法
933
查看次数

标签 统计

c++ ×2

c++11 ×1

functor ×1

lambda ×1

optimization ×1

performance ×1

sorting ×1

stl ×1