美文网首页
使用Fortran加速Python

使用Fortran加速Python

作者: hlyang | 来源:发表于2017-06-29 23:16 被阅读0次

    使用场景

    • 数值运算,特别是多维矩阵运算;
    • 并行运算,使用openmp

    优势

    简单例子

    # flib.f90
    subroutine foo(a, b, c, d, n)
        implicit none
        integer :: n
        real, intent(in) :: a(n,n), b(n,n)
        real, intent(out) :: c(n, n), d(n, n)
        c = matmul(a,b)
        d = matmul(a,b)*2.0d0
    end subroutine foo
    

    将上面的代码保存为flib.f90, 确保Anaconda, numpy已经安装,输入下面的命令:

    f2py -c -m flib flib.f90
    

    上面的命令再linux下会生成flib.so,可以直接导入python

    image.png

    使用OpenMP

    # flib.f90
    subroutine acorr(v,  c,  nstep)
            !$ use omp_lib
            ! (Normalized) 1d-vacf: c_vv(t) = C_vv(t) / C_vv(0)
            integer, parameter :: dp = selected_real_kind(15, 307) ! 64-bit reals
            integer, intent(in) :: nstep, nc
            real(dp), intent(in) :: v(0:nstep-1)
            real(dp), intent(out) :: c(0:nstep-1)
            integer             :: dt
    !$OMP     parallel do
            do dt = 0,nstep-1
                c(dt) = sum(v(0:nstep-dt-1) * v(dt:)) / (nstep-dt)
            end do
    !$OMP     end parallel do
    end subroutine acorr
    
    • 使用ifortopenmp编译:
    f2py -c -m flib flib.f90 --opt='-O3' --fcompiler=intelem --f90flags="-openmp -D__OPENMP" --f77flags="-openmp -D__OPENMP" -liomp5
    
    • 使用gfortranopenmp编译
    f2py -c -m flib flib.f90 --opt='-O3' --fcompiler=gnu95 --f90flags="-fopenmp -D__OPENMP" --f77flags="-fopenmp -D__OPENMP" -lgomp
    

    注意: 上面命令中参数--fcompiler可以使用下面命令查看,不同系统可用的编译器不同:

    f2py -c --help-fcompiler
    

    比如我的系统支持的编译器选项为:

    image.png

    FAQ

    • 传递参数给Fortran subroutine时可以使用assumed shape array吗?
      不可以。

    • 可以使用Allocatable arrays吗?
      可以。参考:Allocatable arrays

    • f2py运行出错了,信息太乱看不到错误信息
      在运行f2py前可以使用下面命令,没有错误信息后再使用f2py

    ifort -c flib.f90
    #or
    gfortran -c flib.f90
    
    • Pythonnumpy默认是按行存储的, 而Fortran数组是按列存储的,需要考虑数组存储的顺序吗?
      一般不用。除非数组非常大,接近物理内存,否则f2py会自动判断是否需要复制数组,具体请参考:Array arguments

    • f2py调用Fortran性能怎么样?
      Linux系统中,编译的时候加上选项-DF2PY_REPORT_ATEXIT,结束的时候会输出如下图的性能报告,计算量较小时, f2py interface所需的时间相对较长, 但计算量很大时,这个时间就不值一提了。

    f2py -c -m flib flib.f90 -DF2PY_REPORT_ATEXIT
    
    image.png

    参考

    相关文章

      网友评论

          本文标题:使用Fortran加速Python

          本文链接:https://www.haomeiwen.com/subject/okbvcxtx.html