[f2py] what's the overhead of passing python callback functions to Fortran subroutines?

Ying Zu <[email protected]> Fri, 23 Sep 2011 02:24:35 -0400
Newsgroups gmane.comp.python.f2py.user
Message-ID <CA+FeNuthzt4jejzvdBYPSRUBJGt9A6AJNZ++q6Qkdua0+pAqTw@mail.gmail.com>
Hi Folks,

I try to wrap a Fortran 90 subroutine using F2PY. The subtlety here is
the Fortran subroutine aslo takes a python call-back function as its
argument.

subroutine f90foo(pyfunc, a)
real(kind=8),intent(in) :: a
!f2py intent(callback) pyfunc
external pyfunc
!f2py real*8 y,x
!f2py y = pyfunc(x)

!*** debug begins***
print *, 'Start Loop'
do i=1,1000
 p = pyfunc(a)
end do
total = etime(elapsed)
print *, 'End: total=', total, ' user=', elapsed(1), ' system=', elapsed(2)
stop
!*** debug ends  ***
The pyfunc is a python function defined elsewhere in my python code.
After using f2py to wrap it into a python module, I got an elapsed
time of factor 5 times longer than what I get using pure python as
follows,
def pythonfoo(k):
    print('Pure Python: Start Loop')
    start = time.time()
    for i in xrange(1000):
        p = pyfunc(k)
    elapsed = (time.time() - start)
    print('End: total=%20f'% elapsed)

So, the question is, what is the overhead coming from? and how to
improve the speed of the wrapper module? Thanks!