Timers in Co-array Fortran
program timers
use iso_fortran_env
implicit none
! We often want to execute code at some point in the future, or repeatedly
! at some interval. Co-array Fortran doesn't have built-in timer features,
! but we can use the SLEEP intrinsic to simulate timers.
! Simulate a timer that waits for 2 seconds
call sleep(2)
print *, "Timer 1 fired"
! If you just wanted to wait, you could have used SLEEP directly.
! One reason a timer might be useful is that you can potentially
! cancel it before it fires. Here's an example of that concept:
logical :: stop2
stop2 = .false.
! Start a "timer" in a separate image
sync all
if (this_image() == 1) then
call sleep(1)
if (.not. stop2) then
print *, "Timer 2 fired"
end if
end if
! On image 2, we "stop" the timer
if (this_image() == 2) then
stop2 = .true.
print *, "Timer 2 stopped"
end if
! Give enough time for the "timer" to fire, if it was going to
sync all
if (this_image() == 1) then
call sleep(2)
end if
end program timers
To compile and run this Co-array Fortran program:
$ caf timers.f90 -o timers
$ cafrun -np 2 ./timers
Timer 1 fired
Timer 2 stopped
The first “timer” will fire ~2s after we start the program, but the second should be stopped before it has a chance to fire.
Note that this is a simplified simulation of timers using Co-array Fortran. The language doesn’t have built-in timer features like some other languages, so we use the SLEEP intrinsic and co-arrays to demonstrate similar concepts. The “stopping” of a timer is simulated using a logical variable shared across images.
In a real-world scenario, you might want to use more sophisticated methods for timing and synchronization, possibly involving MPI libraries or other external timing mechanisms, depending on your specific requirements and the capabilities of your Fortran compiler and runtime environment.