mercredi 31 janvier 2018

why sort in C++ is much slower than qsort in C?

In the book The C++ Programming Language (4th Edition), Stroustrup say that sort is much faster than qsort , but in my experiment, I got a different result, could any one help me to explain Why?

Here is my code :

double begin_time=0, end_time=0, elapsed_time=0;

vector<string> vs1 = { "fsfaa", "errer", "weesa", "yuyre", "wedsa", "xcxcx" };
begin_time = clock();

for (int i = 0; i < 1000000; i++)
{
    std::sort(vs1.begin(), vs1.end());
}

end_time = clock();
elapsed_time = double(end_time - begin_time) / CLOCKS_PER_SEC;

printf("\n\nElapsed time: %f\n", elapsed_time);

const char* vs[] = { "fsfaa", "errer", "weesa", "yuyre", "wedsa", "xcxcx" };
begin_time = clock();

for (int i = 0; i < 1000000; i++)
{
    std::qsort(vs, sizeof(vs) / sizeof(*vs), sizeof(*vs), (int(*)(const void*, const void*))compare_function);
}

end_time = clock();
elapsed_time = double(end_time - begin_time) / CLOCKS_PER_SEC;
printf("\n\nElapsed time: %f\n", elapsed_time);

and,

int compare_function(const void * a, const void * b) {
const char *pa = *(const char**)a;
const char *pb = *(const char**)b;

return strcmp(pa, pb);

}

Here is the result(Windows/Visual Studio):

Elapsed time: 0.245000
Elapsed time: 0.090000

Aucun commentaire:

Enregistrer un commentaire