Created
January 29, 2015 11:50
-
-
Save keisukefukuda/856df0a75089837db194 to your computer and use it in GitHub Desktop.
Compare speeds of "uniq" operation to std::vector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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