Timers in Fortran
Our first example demonstrates the use of timers in Fortran. We’ll use the sleep
subroutine from the iso_c_binding
module to simulate timers.
program timers
use iso_c_binding, only: c_sleep
implicit none
! Simulate a timer that waits for 2 seconds
call timer1()
! Simulate a timer that can be cancelled
call timer2()
contains
subroutine timer1()
integer :: result
! Wait for 2 seconds
result = c_sleep(2)
print *, "Timer 1 fired"
end subroutine timer1
subroutine timer2()
integer :: result
logical :: stop_timer
stop_timer = .true.
if (stop_timer) then
print *, "Timer 2 stopped"
else
! This part would run if the timer wasn't stopped
result = c_sleep(1)
print *, "Timer 2 fired"
end if
! Wait for 2 seconds to show that Timer 2 doesn't fire
result = c_sleep(2)
end subroutine timer2
end program timers
In this Fortran program:
We use the
iso_c_binding
module to access thec_sleep
function, which allows us to pause the program execution.The
timer1
subroutine simulates a timer that waits for 2 seconds usingc_sleep(2)
.The
timer2
subroutine demonstrates a timer that can be cancelled. We use a logical variablestop_timer
to simulate stopping the timer.In the main program, we call both
timer1
andtimer2
.
To run the program:
$ gfortran timers.f90 -o timers
$ ./timers
Timer 1 fired
Timer 2 stopped
The output shows that Timer 1 fires after 2 seconds, while Timer 2 is stopped before it has a chance to fire.
Note that Fortran doesn’t have built-in timer or ticker features like some other languages. In real-world applications, you might use system-specific libraries or more advanced timing modules for precise timing operations.