0

我正在寻找一种纯粹的方式来访问时间信息。我考虑了标准编译器的内在函数和子例程(date_and_time, cpu_time, system_clock, ltime, ctime, ...),格式对我来说并不重要。我也想过MPI函数,但它和内在函数一样,都有不纯的函数。

这是一个最小的例子:

elemental subroutine add(message, text)
  ! function add
  IMPLICIT NONE
  character(len=:),allocatable,intent(inout)   :: message
  character(len=*), intent(in)                 :: text
  character(len=1), parameter                  :: nl=char(10)
  character(10) :: time
  ! character(8)  :: date

  ! time= 'hhmmss.sss'
  call DATE_AND_TIME(time) 
  Message= Message//time////text//nl

end subroutine add

我得到一个逻辑错误:

Error: Subroutine call to intrinsic ‘date_and_time’ at (1) is not PURE  

因此,如果存在一种纯粹的获取时间信息的方法,或者如果不可能纯粹拥有它(可能是因为它必须使用 cpu 信息,由于我不知道的原因,这可能是线程不安全的),我正在徘徊。

也许,一个子问题,是否有一种解决方案可以强制编译器考虑date_and_time纯(或任何其他此类函数)?

4

1 回答 1

3

关于获得时间的纯粹方式的答案是否定的。返回当前时间或日期的函数是不纯的,因为在不同的时间它会产生不同的结果——它指的是某个全局状态。

当然有一些技巧可以让编译器相信子程序是纯的。一种是平铺在接口块中。

但是对编译器撒谎是有后果的。它可以进行不安全的优化,结果将是未定义的(无论如何通常都是正确的,但是......)。

module m
contains

  elemental subroutine add(text)
    IMPLICIT NONE
    character(len=*), intent(in)                 :: text
    character(len=1), parameter                  :: nl=char(10)
    character(10) :: time
          intrinsic date_and_time

    interface
      pure subroutine my_date_and_time(time)
        character(10), intent(out) :: time
      end subroutine
    end interface

    call MY_DATE_AND_TIME(time) 
  end subroutine add

end module

program test
  use m

  call add("test")
end program

subroutine my_date_and_time(time)
  character(10), intent(out) :: time

  call date_and_time(time)

end subroutine

请注意,我必须删除您的message,因为这与elemental.

于 2017-04-25T11:57:28.467 回答