python Easy to write, but speedy ~ → Bottleneck modularized fortran !! !! !! fast! !! !!
Let's modularize the prime number display program I wrote earlier for the purpose of practicing Fortran.
f2py (included with scipy) gfortran4.7.2
Prepare a file that describes the subroutine you want to modularize. The argument of the subroutine declares in with Cf2py. The return value of the subroutine (that is, the return value received on the python side) declares out with Cf2py. If you do not write the Cf2py declaration from the beginning of the line and open 6 spaces in the script body, a compile error will occur. Apparently, I have to write it indented after Cf2py (it's annoying !!)
primepy.f90
subroutine prime_number(max_num, ret)
implicit none
integer max_num
integer ret(max_num)
integer i, j, list(max_num)
Cf2py intent(in) max_num
Cf2py intent(out) ret
!set l
do i=1, max_num, 1
list(i) = i
enddo
list(1) = 0
!Set a prime number
do i=1, max_num, 1
if (.not. list(i) == 0) then
do j = i*2, max_num, i
list(j) = 0
end do
endif
enddo
!Returns a list of prime numbers
do i=1, max_num, 1
ret(i) = list(i)
enddo
end subroutine prime_number
f2py -c --fcompiler=gfortran -m prime primepy.f90
Compile with -c
Specify the compiler with --fcompiler
Output file after -m
Finally the Fortran program files
Then check help with -h
Success if prime.so file is created.
With a python interpreter
>>> import prime
>>> a = prime.prime_number(100)
>>> a
array([ 0, 2, 3, 0, 5, 0, 7, 0, 0, 0, 11, 0, 13, 0, 0, 0, 17,
0, 19, 0, 0, 0, 23, 0, 0, 0, 0, 0, 29, 0, 31, 0, 0, 0,
0, 0, 37, 0, 0, 0, 41, 0, 43, 0, 0, 0, 47, 0, 0, 0, 0,
0, 53, 0, 0, 0, 0, 0, 59, 0, 61, 0, 0, 0, 0, 0, 67, 0,
0, 0, 71, 0, 73, 0, 0, 0, 0, 0, 79, 0, 0, 0, 83, 0, 0,
0, 0, 0, 89, 0, 0, 0, 0, 0, 0, 0, 97, 0, 0, 0], dtype=int32)
Water
I couldn't think of an easy way to return only non-zero, so this is ʻa.take (a.nonzero () [0])` on the python side.
Happy to eliminate bottlenecks If you don't understand with fortran, handle it on the python side! !! The best list of python! !! !!
Recommended Posts