Epoch in Co-array Fortran

A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in Co-array Fortran.

program epoch
  use iso_fortran_env, only: int64
  implicit none

  integer(int64) :: count, count_rate, count_max
  real :: seconds, milliseconds
  integer(int64) :: nanoseconds

  ! Get the current time
  call system_clock(count, count_rate, count_max)

  ! Calculate seconds, milliseconds, and nanoseconds since the epoch
  seconds = real(count) / real(count_rate)
  milliseconds = seconds * 1000
  nanoseconds = int(seconds * 1e9, int64)

  ! Print the results
  print *, "Current time:", count
  print *, "Seconds since epoch:", int(seconds)
  print *, "Milliseconds since epoch:", int(milliseconds)
  print *, "Nanoseconds since epoch:", nanoseconds

  ! Convert back to time
  count = int(seconds * count_rate, int64)
  print *, "Converted back to count:", count

end program epoch

In this Co-array Fortran program:

  1. We use the system_clock subroutine to get the current time. This subroutine returns the number of clock ticks since an arbitrary time in the past.

  2. We calculate the number of seconds by dividing the count by the count rate. This gives us the time in seconds since the arbitrary starting point.

  3. We then calculate milliseconds and nanoseconds based on the seconds value.

  4. We print out these values to show the elapsed time since the arbitrary starting point (which is not necessarily the Unix epoch, but serves a similar purpose in this example).

  5. Finally, we demonstrate how to convert the seconds back to the original count value.

To compile and run the program:

$ gfortran -coarray=single epoch.f90 -o epoch
$ ./epoch
Current time:           1234567890
Seconds since epoch:          1234
Milliseconds since epoch:  1234567
Nanoseconds since epoch: 1234567890000
Converted back to count: 1234567890

Note that the actual output will vary depending on when you run the program and the specifics of your system’s clock.

In Co-array Fortran, we don’t have a built-in way to get the exact Unix epoch time as in some other languages. The system_clock function provides a similar functionality, giving us a consistent time reference from an arbitrary starting point. For many applications, this relative time measurement is sufficient.

Next, we’ll look at another time-related task: time formatting and parsing, which can be implemented using additional modules or custom subroutines in Fortran.