Skip to content

Instantly share code, notes, and snippets.

@ramntry
Created October 30, 2014 22:51
Show Gist options
  • Select an option

  • Save ramntry/a18046a915cf13126119 to your computer and use it in GitHub Desktop.

Select an option

Save ramntry/a18046a915cf13126119 to your computer and use it in GitHub Desktop.
#include <cstddef>
#define max(a, b) (((a) < (b)) ? (b) : (a))
int test(int const *const nums, size_t const size, int const bound1, int const bound2, int const bound3) {
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
for (size_t i = 0; i < size; ++i) {
int const value = nums[i];
if (value < bound2) {
if (value < bound1) {
++counter1;
} else {
++counter2;
}
} else {
if (value < bound3) {
++counter3;
} else {
++counter4;
}
}
}
return max(max(counter1, counter2), max(counter3, counter4));
}
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
void printUsage(char **argv) {
std::cout << "Usage: " << argv[0] << " sorted | unsorted" << std::endl;
}
bool testSorted(int argc, char **argv) {
if (argc != 2) {
printUsage(argv);
exit(EXIT_FAILURE);
}
std::string const arg(argv[1]);
if (arg == "sorted") {
return true;
}
if (arg == "unsorted") {
return false;
}
printUsage(argv);
exit(EXIT_FAILURE);
}
int test(int const *const nums, size_t const size, int const bound1, int const bound2, int const bound3);
volatile int dontThrowItAway;
int main(int argc, char **argv) {
size_t const size = 64*1024;
int const numOfRepetitions = 10*1000;
int const bound1 = RAND_MAX / 4;
bool const benchSorted = testSorted(argc, argv);
std::clog << "Creating data..." << std::endl;
std::vector<int> nums(size);
generate(nums.begin(), nums.end(), rand);
std::vector<int> sorted(nums);
sort(sorted.begin(), sorted.end());
std::clog << "Benching";
if (benchSorted) {
for (int i = 0; i < numOfRepetitions; ++i) {
dontThrowItAway = test(&sorted[0], size, bound1, 2 * bound1, 3 * bound1);
if ((i + 1) % (numOfRepetitions / 50) == 0) {
std::clog << ".";
}
}
} else {
for (int i = 0; i < numOfRepetitions; ++i) {
dontThrowItAway = test(&nums[0], size, bound1, 2 * bound1, 3 * bound1);
if ((i + 1) % (numOfRepetitions / 50) == 0) {
std::clog << ".";
}
}
}
std::clog << std::endl;
}
bench: bench.o main.o
g++ $^ -o $@
bench.o: bench.cpp
g++ -c -o $@ $^
main.o: main.cpp
g++ -c -O3 -o $@ $^
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment