user1542266
user1542266

Reputation:

Does gfortran generate random numbers more slowly than MATLAB?

I am a first-time user of Fortran and am performing an elementary performance comparison of Fortran vs. Matlab by sampling random numbers (suppressed output). With an MWE, in Fortran (.f95 file):

program main
  real(4) :: r
  integer i
  do i = 1,50000000
    call random_number(r)
  enddo
end program main

And in MATLAB (.m file):

for i = 1:50000000
  rand();
end

When I compile the Fortran code using gfortran (v4.5.3), the executable runs about 3x slower than the MATLAB (r2011b) code. As it stands, is this an expected outcome?

Upvotes: 0

Views: 736

Answers (1)

Oleg2718281828
Oleg2718281828

Reputation: 1039

As IanH pointed out, you are actually comparing single and double precision. If I change your Fortran code to double precision, I get an extra ~2x slow-down.

The reason for the speed difference is probably the fact that Matlab and gfortran use different implementations of different algorithms: Matlab uses the Mersenne twister PRNG, whereas gfortran uses George Marsaglia's KISS PRNG.

Upvotes: 4

Related Questions