Nugroho's blog.: Compare Native Loop Time in Python with "homemade" Fortran Module

Monday, December 22, 2014

Compare Native Loop Time in Python with "homemade" Fortran Module

This code print d and e as result of two matrix addition, e's using python native code, d's using fortran module compiled with F2PY

The code
import numpy as np
import aravir as ar
import time

n = 1000

u = np.ones((n,n))
v = np.ones((n,n))
e = np.ones((n,n))

t = time.clock()
d = ar.add3(u,v)
tfortran= time.clock()-t

t = time.clock()
for i in range (n):
for j in range (n):
e[i,j] = u[i,j]+v[i,j]
tnative = time.clock()-t

print 'fortran ', d
print 'native', e
print 'tfortran = ', tfortran, ', tnative = ', tnative


The fortran module I imported to python
        subroutine add3(a, b, c, n)
double precision a(n,n)
double precision b(n,n)
double precision c(n,n)

integer n
cf2py intent(in) :: a,b
cf2py intent(out) :: c,d
cf2py intent(hide) :: n
do 1700 i=1, n
do 1600 j=1, n
c(i,j) = a(i,j)
$ +b(i,j)

1600 continue
1700 continue
end

save it as aravir.f and compile using
$ f2py -c aravir.f -m aravir

And here the result
$ python cobamodul.py 
fortran [[ 2. 2. 2. ..., 2. 2. 2.]
[ 2. 2. 2. ..., 2. 2. 2.]
[ 2. 2. 2. ..., 2. 2. 2.]
...,
[ 2. 2. 2. ..., 2. 2. 2.]
[ 2. 2. 2. ..., 2. 2. 2.]
[ 2. 2. 2. ..., 2. 2. 2.]]
native [[ 2. 2. 2. ..., 2. 2. 2.]
[ 2. 2. 2. ..., 2. 2. 2.]
[ 2. 2. 2. ..., 2. 2. 2.]
...,
[ 2. 2. 2. ..., 2. 2. 2.]
[ 2. 2. 2. ..., 2. 2. 2.]
[ 2. 2. 2. ..., 2. 2. 2.]]
tfortran = 0.069974 , tnative = 1.202547

The Desktop, :)


No comments:

323f (5) amp (1) android (12) apple (7) arduino (18) art (1) assembler (21) astina (4) ATTiny (23) blackberry (4) camera (3) canon (2) cerita (2) computer (106) crazyness (11) debian (1) delphi (39) diary (286) flash (8) fortran (6) freebsd (6) google apps script (8) guitar (2) HTML5 (10) IFTTT (7) Instagram (7) internet (12) iOS (5) iPad (6) iPhone (5) java (1) javascript (1) keynote (2) LaTeX (6) lazarus (1) linux (29) lion (15) mac (28) macbook air (8) macbook pro (3) macOS (1) Math (3) mathematica (1) maverick (6) mazda (4) microcontroler (35) mountain lion (2) music (37) netbook (1) nugnux (6) os x (36) php (1) Physicist (29) Picture (3) programming (189) Python (109) S2 (13) software (7) Soliloquy (125) Ubuntu (5) unix (4) Video (8) wayang (3) yosemite (3)