Skip to content

Instantly share code, notes, and snippets.

@ridiculousfish
Last active August 29, 2015 14:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ridiculousfish/bb511993deba1d148317 to your computer and use it in GitHub Desktop.
Save ridiculousfish/bb511993deba1d148317 to your computer and use it in GitHub Desktop.
sort vs sort
// c++ -std=c++11 -O3 sort.cpp ; ./a.out
// qsort: 674 ms
// std::sort: 1104 ms
#include <string.h>
#include <stdio.h>
#include <chrono>
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
static unsigned long long now()
{
return chrono::system_clock::now().time_since_epoch() / chrono::milliseconds(1);
}
static int compare_strings(const void *a, const void *b)
{
const string *s1 = *(string **)a;
const string *s2 = *(string **)b;
return strcmp(s1->c_str(), s2->c_str());
}
int main(void)
{
unsigned long long start, end;
string s(10000, 'x');
vector<string *> v(1000000, &s);
start = now();
qsort(&v[0], v.size(), sizeof v[0], compare_strings);
end = now();
printf("qsort: %llu ms\n", end - start);
start = now();
sort(v.begin(),v.end(),[](const string *x, const string *y) { return *x > *y; });
end = now();
printf("std::sort: %llu ms\n", end - start);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment