#include <iostream>
#include <ctime>
#include <vector>
#include <algorithm>
#include <iterator>
#include <numeric>
#include <cassert>
using namespace std;
const int ARRAY_SIZE = 10000;
const int FIND_SMALLEST = 300;
const int RUN_N_TIMES = 10000;
float average_of_k_smallest(float* arr, int n, int k);
float average_of_k_smallest_partial_sort(vector<float> arr, int n);
int main(int argc, char* argv[]) {
clock_t begin, end;
float res;
srand(time(NULL));
float array[ARRAY_SIZE];
vector<float> array_v(ARRAY_SIZE);
// load the array with random data
for(int i = 0; i < ARRAY_SIZE; ++i) {
array[i] = (float)rand()/(float)RAND_MAX; // random numbers from 0..1
array_v[i] = array[i];
}
begin = clock();
for(int i = 0; i < RUN_N_TIMES; ++i) {
// Make a copy of the array due to array being passed by reference.
float array_copy[ARRAY_SIZE];
copy(&array[0], &array[ARRAY_SIZE], &array_copy[0]);
res = average_of_k_smallest(array_copy, ARRAY_SIZE, FIND_SMALLEST);
}
end = clock();
cout << "Original function: (" << res << ") " << (float)(end - begin)/CLOCKS_PER_SEC << " sec" << endl;
begin = clock();
for(int i = 0; i < RUN_N_TIMES; ++i) {
// Make a copy of the array
vector<float> array_copy(array_v);
res =average_of_k_smallest_partial_sort(array_copy, FIND_SMALLEST);
}
end = clock();
cout << "STL function: (" << res << ") " << (float)(end - begin)/CLOCKS_PER_SEC << " sec" << endl;
return 0;
}
// Returns the average of k smallest values from the array arr of size n.
// The original order of elements in arr is not guaranteed to be preserved.
float average_of_k_smallest(float *arr, int n, int k) {
assert(k > 0 && k <= n);
std::sort(arr, arr + n);
float s = 0.0f;
for (int i = 0; i < k; i++) s += arr[i];
return s/k;
}
float average_of_k_smallest_partial_sort(vector<float> arr_v, int k) {
partial_sort(arr_v.begin(), arr_v.begin()+k, arr_v.end());
float sum = accumulate(arr_v.begin(), arr_v.begin()+k, 0.0);
return sum/k;
}
Recent Comments