Timing a Fortran function

How to time a Fortran function? Here’s a Fortran program which times an execution of Ackermann’s function. It uses two calls to Fortran’s cpu_time() function. The result is in seconds.

Easy right? (Way easier than C).

program runtime
  implicit none

  integer :: m, n, ans
  real :: startT, endT, execTime

  write(*,*) 'Recursive Ackermann in Fortran'
  write(*,*) 'Enter First Value (m) and Second Value (n)'
  read(*,*) m, n

  call cpu_time(startT)
  ans = ackermann(m,n)
  call cpu_time(endT)
  execTime = (endT - startT)

  write(*,*) 'The value is: ', ans
  write(*,*) 'Elapsed time in seconds: ', execTime

contains

recursive function ackermann(m,n) result(a)

  integer :: m,n
  integer :: a

  if (m==0) then
    a = n + 1
  else if (n==0) then
    a = ackermann(m-1, 1)
  else
    a = ackermann(m-1, ackermann(m, n-1))
  end if

end function ackermann

end program runtime

Here’s a sample output:

Recursive Ackermann in Fortran
Enter First Value (m) and Second Value (n)
3 2
The value is: 29
Elapsed time in seconds: 8.00006092E-06

Here’s another run:

Recursive Ackermann in Fortran
Enter First Value (m) and Second Value (n)
4 1
The value is: 65533
Elapsed time in seconds: 20.9853764

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s