Skip to content

Instantly share code, notes, and snippets.

@keisukefukuda
Created January 29, 2015 11:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keisukefukuda/856df0a75089837db194 to your computer and use it in GitHub Desktop.
Save keisukefukuda/856df0a75089837db194 to your computer and use it in GitHub Desktop.
Compare speeds of "uniq" operation to std::vector
#include <cstdlib>
#include <ctime>
#include <cassert>
#include <sys/time.h>
#include <unistd.h>
#include <set>
#include <vector>
#include <algorithm>
#include <iostream>
#include <iomanip>
using namespace std;
vector<int> uniq_set(const vector<int> &v) {
set<int> s(begin(v), end(v));
return vector<int>(begin(s), end(s));
}
vector<int> uniq_erase(const vector<int> &v) {
vector<int> v2(v);
v2.erase(unique(begin(v2), end(v2)), end(v2));
return v2;
}
double wtime() {
struct timeval t;
gettimeofday(&t, NULL);
return t.tv_sec + 1e-6*t.tv_usec;
}
#define measure(stmt, res) do { \
double __t1 = wtime(); \
stmt; \
double __t2 = wtime(); \
res = __t2 - __t1; \
} while(0)
int main(int argc, char**argv) {
assert(argc == 2);
srand(time(NULL));
const auto N = atol(argv[1]);
vector<int> v(N);
for (int i = 0; i < N; i++) {
v[i] = rand() % (N/10);
}
sort(begin(v), end(v));
double t1, t2;
measure(uniq_erase(v), t1);
measure(uniq_set(v), t2);
cout << "uniq_erase : " << scientific << t1 << " sec." << endl;
cout << "uniq_set : " << scientific << t2 << " sec." << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment