Time Functions

Modern Fortran features some basic time functions. On POSIX-compliant systems, the ISO C binding interface allows us to use additional timing routines defined by libc.


The sleep routine pauses the program for a given number of seconds:

! time.f90
program main
    call sleep(5) ! sleep for 5 seconds
end program main

In order to sleep for less than a second, one can write an interface to the libc routine usleep(), which pauses for a given interval measured in microseconds:

! posix_sleep.f90
program main
    implicit none
    integer :: i
    integer :: t = 500000 ! 500 milliseconds

        subroutine usleep(useconds) bind(c)
            use, intrinsic :: iso_c_binding, only: c_int32_t
            implicit none
            integer(c_int32_t), value :: useconds
        end subroutine
    end interface

    do i = 1, 10
        print '(a)', 'zzz ...'
        call microsleep(t)
    end do

        subroutine microsleep(useconds)
            !! Wrapper for `usleep()` that converts integer to c_int32_t.
            use, intrinsic :: iso_c_binding, only: c_int32_t
            implicit none
            integer :: useconds
            call usleep(int(useconds, kind=c_int32_t))
        end subroutine microsleep
end program main

You may want to write a wrapper routine like microsleep() that does the type convertion from integer to c_int32_t.

CPU Time

The intrinsic Fortran routine cpu_time() returns the ellapsed CPU time in microseconds.

! cpu.f90
program main
    implicit none
    real :: t1, t2

    call cpu_time(t1)

    ! do some calculations ...
    do i = -1000000, 1000000
        x = sqrt(sin(real(i))**2 + 1/cos(real(i))**2)
    end do

    call cpu_time(t2)

    print '("Time = ", f8.6, " seconds.")', t2 - t1
end program main