昊漫玉 发表于 2017-4-26 13:11:50

python调用c 和fortran

详细请点击:http://www.verydemo.com/demo_c122_i33874.html
  上篇里面写的是python调用c,对速度又很大的提升。
  今天无聊又写了个python调用fortran的来比较比较。
  首先,编写名为test_f.f90的fortran文件:(插入代码居然没有fortran)

!subroutine
    subroutine is_prime(n,value)
        implicit none
        integer::n,i,value
!f2py   intent(in)::n
!f2py   intent(out)::value
        if(mod(n,2)==0) then
            value=0
            return 
        else
            do i=3,int(sqrt(float(n)))+1,2
                if(mod(n,i)==0) then
                    value=0
                    return 
                end if
            end do
        end if
        value=1
    end subroutine
  编译fortran文件得到test_f90.so文件:
  ....................................................................

f2py -m test_f -c test_f.f90
  最后编写测试文件:

import test_f
def test_f90():
    ti=time.time()
    count=0
    for i in xrange(3,10000000):
        if test_f.is_prime(i):
            count+=1
    return "test_f90: time=%s   ;count=%s"%(time.time()-ti,count)
  测试判断一千万个素数:
  #'test_c: time=14.7924110889    ;count=664578'
  #'test_f90: time=6.10868906975   ;count=664578'
  #可以看出调用.f90的速度是.c的2倍还多。
  #并且调用.f90也相对简
页: [1]
查看完整版本: python调用c 和fortran