Monday, January 14, 2013

Boost.python vs. python simple function exec time comparison

Last time i've decided to compare execution time of simple functions written in Python and C++. To do that i've created simple c++ code exposed as python module by Boost.python library.

 #include <algorithm>  
 #include <boost/python.hpp>  
 int gcd(int a,int b){  
   if (b!=0)  
     return gcd(b,a%b);  
   else  
     return a;  
 }  
 BOOST_PYTHON_MODULE(cpp_compare)  
 {  
   using namespace boost::python;  
   def("max",   
     std::max<int>,return_value_policy<copy_const_reference>());  
   def("gcd",gcd);  
 }  
Module can be compiled on Linux with following Sconstruct file


 # Przemek  -*- mode: Python; -*-  
 ##Linux Parameters  
 boost_path='/usr/include/boost/'  
 python_path='/usr/include/python2.7/'  
 ##End  
 import platform, os  
 boost_libs=['boost_python']  
 env = Environment()  
 if(platform.system() == "Linux"):  
   env.Append(CPPPATH=[boost_path,python_path])  
 #modul pythona  
   env.SharedLibrary(target='cpp_compare.so',source=['python_wraper.cpp'], LIBS=boost_libs, SHLIBPREFIX='')  
 else:  
   print platform.system() + ' not supported'  
Last but not least comes Python file:
 import random  
 import cpp_compare  
 import datetime  
 capacity= 1000000  
 min_val = -10000  
 max_val = 100000  
 compare_data = [(int(random.randint(min_val,max_val)), int(random.randint(min_val,max_val))) for i in xrange(capacity)]  
 def gcd(a, b):  
   if b!=0:  
     return gcd(b, a%b)  
   else:  
       return a  
 def compare_time(fun_name, python_fun, cpp_fun):   
     print 'Comparing ', fun_name,' execution time:'  
     start= datetime.datetime.now()  
     for i, j in compare_data:  
       python_fun(i,j)#bigger = max(i, j)  
     end = datetime.datetime.now()  
     print 'Python time:', (end-start).total_seconds()  
     start= datetime.datetime.now()  
     for i, j in compare_data:  
        cpp_fun(i,j)#bigger = cpp_compare.max(i, j)  
     end = datetime.datetime.now()  
     print 'Cpp time:',(end-start).total_seconds()  
 compare_time('Max',max, cpp_compare.max)  
 compare_time('Greatest common divisor',gcd, cpp_compare.gcd)  
Results from executing python main.py
Comparing Max execution time:
Python time: 0.283549
Cpp time: 0.589304

Comparing Greatest common divisor execution time:
Python time: 4.236021
Cpp time: 0.746045

Results seems to be pretty obvious. Simple calculations like MAX should be written using native Python packages. Probably most of time was wasted to call cpp module. But when calculations are more complicated, its worth to write them in C++.

No comments:

Post a Comment