有时间纯用 Fortran 语言吗?
Have time in a pure manner in Fortran?
我正在寻找一种访问时间信息的纯粹方式。我想到了标准编译器的内在函数和子程序(date_and_time
、cpu_time
、system_clock
、ltime
、ctime
、...),格式不对我来说真的很重要。我也想过MPI函数,不过和intrinsic functions一样,都是impure functions。
这是一个最小的例子:
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
纯函数(或任何其他此类函数)?
关于获取时间的纯粹方式的答案是否。 returns 当前时间或日期的函数是不纯的,因为在不同的时间它会产生不同的结果——它指的是一些全局状态。
肯定有一些技巧可以说服编译器子程序是纯子程序。一种是平铺在一个接口块中。
但是对编译器说谎是有后果的。它可以进行不安全的优化,结果将是不确定的(无论如何通常都是正确的,但是......)。
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
绝对不兼容。
我正在寻找一种访问时间信息的纯粹方式。我想到了标准编译器的内在函数和子程序(date_and_time
、cpu_time
、system_clock
、ltime
、ctime
、...),格式不对我来说真的很重要。我也想过MPI函数,不过和intrinsic functions一样,都是impure functions。
这是一个最小的例子:
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
纯函数(或任何其他此类函数)?
关于获取时间的纯粹方式的答案是否。 returns 当前时间或日期的函数是不纯的,因为在不同的时间它会产生不同的结果——它指的是一些全局状态。
肯定有一些技巧可以说服编译器子程序是纯子程序。一种是平铺在一个接口块中。
但是对编译器说谎是有后果的。它可以进行不安全的优化,结果将是不确定的(无论如何通常都是正确的,但是......)。
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
绝对不兼容。