00001 #include <iostream>
00002 #include <algorithm>
00003 #include <vector>
00004 #include <cstdlib>
00005 using namespace std;
00006
00007 int get_rand()
00008 {
00009 double rnorm = ((double)rand())/((double)RAND_MAX);
00010 return (int)(rnorm*1000.0);
00011 }
00012
00013 class select_func {
00014 int m_min, m_max;
00015 public:
00016 select_func(int min, int max) : m_min(min), m_max(max) {}
00017 ~select_func() {}
00018 bool operator()(int x) { return x >= m_min && x < m_max; }
00019 };
00020
00021 class CpuHog {
00022 vector<int> m_data;
00023 public:
00024
00025 void fill_data() {
00026 for (int i = 0; i < 1e6; ++i) {
00027 m_data.push_back(get_rand());
00028 }
00029 }
00030 void sort_data() {
00031 sort(m_data.begin(),m_data.end());
00032 }
00033 void select_data(int min, int max) {
00034 typedef vector<int> VI;
00035
00036 VI::iterator first=m_data.begin(), last = m_data.end();
00037 VI::iterator middle = partition(first,last,
00038 select_func(min,max));
00039 VI new_data;
00040 back_insert_iterator<VI> vii(new_data);
00041 copy(first,middle,vii);
00042 m_data = new_data;
00043 }
00044 void dump_data() {
00045 cout << "There are " << m_data.size() << " data elements\n";
00046 }
00047 };
00048
00049 void cpu_hog(int min, int max)
00050 {
00051 CpuHog ch;
00052
00053 ch.fill_data();
00054
00055 #ifdef OPTIMIZE
00056 ch.select_data(min,max);
00057 ch.sort_data();
00058 #else
00059 ch.sort_data();
00060 ch.select_data(min,max);
00061 #endif
00062 ch.dump_data();
00063 }
00064
00065 void runner1()
00066 {
00067 int x1 = get_rand(), x2 = get_rand();
00068 if (x1 < x2) cpu_hog(x1,x2);
00069 else cpu_hog(x2,x1);
00070 }
00071 void runner2()
00072 {
00073 int x1 = get_rand(), x2 = get_rand();
00074 if (x1 < x2) cpu_hog(x1,x2);
00075 else cpu_hog(x2,x1);
00076 }
00077
00078 void run_it()
00079 {
00080 vector<int> blah;
00081 for (int i = 0; i < 1e6; ++i) blah.push_back(get_rand());
00082 sort(blah.begin(),blah.end());
00083 cout << "Uselessly sorted 1e6 ints\n";
00084
00085 for (int run = 0; run < 10; ++run) {
00086 if (run%2) runner1();
00087 else runner2();
00088 }
00089 }
00090
00091 int main (int argc, char *argv[])
00092 {
00093 run_it();
00094 }