Thursday, 3 February 2011

boost::spirit vs. atol()

Code taken from this post and modified to check a list of random values...


#include <time.h>

#include <boost/spirit/include/qi.hpp>
#include <iostream>

#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>

#include <list>
#include <string>

std::list<int> test_i;
std::list<std::string> test_s;

void test_spirit(int rep)
{
int val=0;
time_t t=time(NULL);
printf ("test_spirit() begin\n");

for (int r=0; r<rep; r++)
{
std::list<int>::iterator i=test_i.begin();
for(std::list<std::string>::iterator s=test_s.begin(); s!=test_s.end(); s++)
{
boost::spirit::qi::parse ((*s).begin(), (*s).end(), boost::spirit::int_, val);

if (val != *i)
std::cout << "Spirit Errror! val=" << val << std::endl;
i++;
}
};
printf ("test_spirit() end. seconds elapsed=%d\n", time(NULL)-t);
}

void test_atol(int rep)
{
long val=0;
time_t t=time(NULL);

printf ("test_atol() begin\n");

for (int r=0; r<rep; r++)
{
std::list<int>::iterator i=test_i.begin();
for(std::list<std::string>::iterator s=test_s.begin(); s!=test_s.end(); s++)
{
val=atoi((*s).c_str());
if (val != *i)
std::cout << "Atoi Errror! val=" << val << std::endl;
i++;
}
};

printf ("test_atol() end. seconds elapsed=%d\n", time(NULL)-t);
}

int main(int argc, char *argv[])
{
printf ("generating test\n");
for (int i=0; i<5000000; i++)
{
int r=rand();
test_i.push_back (r);
test_s.push_back(str(boost::format ("%d") % r ));
};
test_atol(100);
test_spirit(100);
return 0;
}


Boost 1.45, MSVC 2008, compiling with /Ox flag, results:


generating test
test_atol() begin
test_atol() end. seconds elapsed=34
test_spirit() begin
test_spirit() end. seconds elapsed=50