Skip to content

Instantly share code, notes, and snippets.

@facontidavide
Last active November 22, 2017 13:35
Show Gist options
  • Save facontidavide/bffde5968e0caa6988082d7615e4a477 to your computer and use it in GitHub Desktop.
Save facontidavide/bffde5968e0caa6988082d7615e4a477 to your computer and use it in GitHub Desktop.
Trying (for fun) to re-implement something similar to std::partial_sort_copy
#include <iostream>
#include <vector>
#include <algorithm>
#include <assert.h>
#include <benchmark/benchmark.h>
static std::vector<int> CreateShuffledVector(unsigned n)
{
std::vector<int> vect(n);
for (unsigned i=0; i<n; i++) vect[i] = i;
std::random_shuffle ( vect.begin(), vect.end() );
return vect;
}
// Find the N largest (or smalles) elements in the input vector (vect),
// where vect is NOT sorted, and N = out.size().
// for example, given a random vector 9,7,3,4,0,6,2,8,1,5, and
// out.size() == 3,
// std::greater<int> operation and out.size() == 3,
// The vector out should contain 9,8,7 if std::greater<int> is passed as 3rd parameter
// or 0,1,2 if std::less<int> is passed as 3rd parameter.
template <typename T, typename Comp>
void My_PartialSortCopy(const std::vector<T>& vect, std::vector<T>& out, Comp comparator)
{
const size_t N = out.size();
assert( N <= vect.size() );
//TODO my implementation
}
template <typename T, typename Comp>
void STL_PartialSortCopy(const std::vector<T>& vect, std::vector<T>& out, Comp comparator)
{
const size_t N = out.size();
assert( N <= vect.size() );
std::partial_sort_copy(vect.begin(), vect.end(),
out.begin(), out.end(),
comparator);
}
//-----------------------------------------------
const int S = 10000;
const int M = 1000;
static void BM_Mine(benchmark::State& state) {
const std::vector<int> vect = CreateShuffledVector(S);
std::vector<int> out(M);
for (auto _ : state)
{
My_PartialSortCopy(vect, out, std::greater<int>());
}
benchmark::DoNotOptimize(out);
//test your implementation
std::vector<int> test_out(M);
STL_PartialSortCopy(vect, test_out, std::greater<int>());
for (int i=0; i<M; i++)
{
assert( test_out[i] == out[i] );
}
}
// Register the function as a benchmark
BENCHMARK(BM_Mine);
// Define another benchmark
static void BM_PartialSort(benchmark::State& state) {
const std::vector<int> vect = CreateShuffledVector(S);
std::vector<int> out(M);
for (auto _ : state)
{
STL_PartialSortCopy(vect, out, std::greater<int>());
}
benchmark::DoNotOptimize(out);
}
BENCHMARK(BM_PartialSort);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment