根据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) 我做了一个小测试来检查全局函数/ 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)