compiler vc2010 and gcc4.5.2(minGW)
os : windows xp sp3
I am trying to implement a generic find_if function as std::find_if
Below is my code
//code for estimating expanding time
template<typename unaryOP>
double timeCount(unaryOP op, size_t const LOOP = 1, char const* NAME = "function")
{
std::clock_t begin, end;
begin = std::clock();
for(size_t i = 0; i != LOOP; ++i) op();
end = std::clock();
double const RESULT = (end - begin) / static_cast<double>(CLOCKS_PER_SEC);
size_t const HOUR = static_cast<size_t>(RESULT / 3600);
size_t const MIN = static_cast<size_t>(RESULT) / 60 - HOUR * 60;
double const SEC = RESULT - static_cast<double>(MIN * 60 + HOUR * 3600);
std::cout<<"time of the(hours : min : sec) "<<NAME<<" : "<<HOUR<<" : "<<MIN<<" : "<<SEC;
std::cout<<"\nloop "<<LOOP<<" times\n";
return RESULT;
}
int findInt(void const *DATA)
{
if(*(int*)DATA > 10000) return 1;
else return 0;
}
void* CFind(void *base, size_t const NUM, size_t const SIZE, int(*compare)(void const *DATA) )
{
size_t i = 0;
for(i = 0; i != NUM; ++i)
{
if(compare(base)) break;
base = (char*)(base) + SIZE;
}
return base;
}
void testCFind()
{
int data[] = {1, 20, 33, 55, 22, 77, 88, 99, 3000, 8880, 800, 777, 345, 976, 345, 222, 111, 0, 77, 88, 99, 1, 2, 3, 20000};
size_t i = 0;
size_t const NUM = 1E6;
for(i = 0; i != NUM; ++i) void *temp = CFind(&data[0], sizeof(data) / sizeof(*data), sizeof(*data), findInt);
}
class IntFind : public std::unary_function<int, bool>
{
public :
bool const operator()(int const A) const {return A > 10000;}
};
template<typename inItr, typename predicate>
inItr myFind_if(inItr first, inItr last, predicate pred)
{
while(first != last)
{
if(pred(*first)) break;
++first;
}
return first;
}
void testCPPFind()
{
int data[] = {1, 20, 33, 55, 22, 77, 88, 99, 3000, 8880, 800, 777, 345, 976, 345, 222, 111, 0, 77, 88, 99, 1, 2, 3, 20000};
size_t const NUM = 1E6;
for(size_t i = 0; i != NUM; ++i)
auto it = std::find_if(&data[0], &data[0] + sizeof(data) / sizeof(*data), IntFind());
//auto it = myFind_if(&data[0], &data[0] + sizeof(data) / sizeof(*data), IntFind());
}
void testCPPFind2()
{
int data[] = {1, 20, 33, 55, 22, 77, 88, 99, 3000, 8880, 800, 777, 345, 976, 345, 222, 111, 0, 77, 88, 99, 1, 2, 3, 20000};
size_t const NUM = 1E6;
for(size_t i = 0; i != NUM; ++i)
auto it = myFind_if(&data[0], &data[0] + sizeof(data) / sizeof(*data), IntFind());
}
int main()
{
timeCount(testCPPFind, 1E2, "testCPPFind");
timeCount(testCPPFind2, 1E2, "testCPPFind2");
timeCount(testCFind, 1E7, "testCFind");
std::cout<<"system pause"<<std::endl;
std::cin.get();
return 0;
}
The results of vc2010 are
testCPPFind = 2.031;
testCPPFind2 = 1.969;
testCFind = 0.047;
The results of GCC are almost equal
What makes the speed of CFind far more faster than myFind_if and std::findif?
Thanks a lot