I wrote a py extension to calculate fibonacci sequence (i.e. 1 1 2 3 5 ... ) as following

however, I found it is too slow as the table says

 

so, what is the problem? Diid I do something wrong? thanks

 

M    | speed for pure py | speed for pycxx

-----+-----------------------+--------------------

30    |      0.93 sec          |         6.35 sec

40    |     116.64 sec       |        789.91 sec

 

 

[py code]

import time

def fib(n):
    if n<=1:
        return 1
    else:
        return fib(n-1)+fib(n-2)

print fib(M)
st=time.time()
for i in range(M):
    fib(i)
et=time.time()
print 'pure py=%.2f secs' % (et-st)

[/py code]

 

 

[pycxx code]

#ifdef _MSC_VER

#pragma warning(disable: 4786)

#endif

 

#include "CXX/Objects.hxx"

#include "CXX/Extensions.hxx"

 

class fib_module : public Py::ExtensionModule<fib_module>{

public:

    fib_module():Py::ExtensionModule<fib_module>( "fib" ){

    add_varargs_method("fib", &fib_module::fib, "fibonacci sequence function");

    initialize( "this is the test module" );

  }

 

  virtual ~fib_module(){}

 

private:

    Py::Object fib (const Py::Tuple &args){

        args.verify_length(1);

        Py::Long res = args[0];

        if (res<=Py::Long(1))  return Py::Long(1);

        else{

            Py::Tuple a(1), b(1); a[0]=Py::Long(res-2); b[0]=Py::Long(res-1);

            return fib(a)+fib(b);

        }

    }

};

 

#if defined( _WIN32 )

#define EXPORT_SYMBOL __declspec( dllexport )

#else

#define EXPORT_SYMBOL

#endif

 

extern "C" EXPORT_SYMBOL void initfib(){

#if defined(PY_WIN32_DELAYLOAD_PYTHON_DLL)

    Py::InitialisePythonIndirectPy::Interface();

#endif

    static fib_module* fib = new fib_module;

}

 

extern "C" EXPORT_SYMBOL void initfib_d(){ initfib(); }

[/pycxx code]