Implementing get_walltime in Fortran

Viewed 438

I'm writing a Fortran program based on the first exercise in this book (page 34). The book is designed as an introduction to high performance computing. The first exercise asks the user to write code to estimate pi. Following what is provided by the authors, I have done this successfully.

program compute_pi
   double precision :: x, delta_x, sum
   !double precision :: S,E,MFLOPS
    integer, parameter :: SLICES=10000000
    sum = 0.d0 ; delta_x = 1.d0/SLICES
    !call get_walltime(S)
    do i=0,SLICES-1
        x = (i+0.5)*delta_x
        sum = sum + 4.d0 / (1.d0 + x*x)
    enddo
    pi = sum*delta_x 
    print *, pi
    !call get_walltime(E)
    !MFLOPS = R*N*2.d0/((E-S)*1.d6)
end program compute_pi

Next, I am trying to compute performance in MFlops/sec. In order to do this, I have followed the author's example on page 5 and wrote

program compute_pi
   double precision :: x, delta_x, sum
   double precision :: S,E,MFLOPS
    integer, parameter :: SLICES=10000000
    sum = 0.d0 ; delta_x = 1.d0/SLICES
    call get_walltime(S)
    do i=0,SLICES-1
        x = (i+0.5)*delta_x
        sum = sum + 4.d0 / (1.d0 + x*x)
    enddo
    pi = sum*delta_x 
    print *, pi
    call get_walltime(E)
    MFLOPS = R*N*2.d0/((E-S)*1.d6)
end program compute_pi

When I run the above code in Netbeans (the IDE I am using for Fortran), it returns

undefined reference to `get_walltime_'

I'm not sure why the reference is undefined.

2 Answers

Here's a pure Fortran implementation of get_walltime (only compile-tested):

subroutine get_walltime(wctime)
  use iso_fortran_env, only: int64
  implicit none
  integer, parameter :: dp = kind(1.0d0)
  real(dp) :: wctime
  integer(int64) :: r, c
  call system_clock(c, r)
  wctime = real(c, dp) / r
end subroutine get_walltime

Even better, put it into a module to get interface checking for free. Or even better than that, just call system_clock directly.

The get_wallclock() in that exercise is a call to a C-code that calculated wall-clock time using gettimeofday() from <sys/time.h>. Flip to page 6 of the same book for an example on how to implement that function. Afterwards, compile your C-code with the -c flag to get the object file, e.g. get_wallclock.o. Then link your main Fortran program to the object file. This way the linker can resolve get_walltime().

Related