在Fortran睡觉

Bri*_*ett 16 fortran fortran-iso-c-binding

有没有人知道在Fortran中以一定的毫秒数睡眠的方法?我不想使用非便携式系统调用,因此Fortran或C库固有的任何东西都是首选.

M. *_* B. 12

使用Fortran ISO C绑定使用C库睡眠以秒为单位进行睡眠:

   module Fortran_Sleep

   use, intrinsic :: iso_c_binding, only: c_int

   implicit none

   interface

      !  should be unsigned int ... not available in Fortran
      !  OK until highest bit gets set.
      function FortSleep (seconds)  bind ( C, name="sleep" )
          import
          integer (c_int) :: FortSleep
          integer (c_int), intent (in), VALUE :: seconds
      end function FortSleep

   end interface

end module Fortran_Sleep


program test_Fortran_Sleep

   use, intrinsic :: iso_c_binding, only: c_int

   use Fortran_Sleep

   implicit none

   integer (c_int) :: wait_sec, how_long

   write (*, '( "Input sleep time: " )', advance='no')
   read (*, *) wait_sec
   how_long = FortSleep ( wait_sec )

   write (*, *) how_long

   stop

end program test_Fortran_Sleep
Run Code Online (Sandbox Code Playgroud)


mil*_*cic 5

您可以使用Fortran标准内部函数来执行此操作而无需C绑定:

program sleep
!===============================================================================
implicit none
character(len=100) :: arg ! input argument character string
integer,dimension(8) :: t ! arguments for date_and_time
integer :: s1,s2,ms1,ms2  ! start and end times [ms]
real :: dt                ! desired sleep interval [ms]
!===============================================================================
! Get start time:
call date_and_time(values=t)
ms1=(t(5)*3600+t(6)*60+t(7))*1000+t(8)

! Get the command argument, e.g. sleep time in milliseconds:
call get_command_argument(number=1,value=arg)
read(unit=arg,fmt=*)dt

do ! check time:
  call date_and_time(values=t)
  ms2=(t(5)*3600+t(6)*60+t(7))*1000+t(8)
  if(ms2-ms1>=dt)exit
enddo
!===============================================================================
endprogram sleep
Run Code Online (Sandbox Code Playgroud)

假设可执行文件是slp:

~$ time slp 1234

real        0m1.237s
user        0m1.233s
sys         0m0.003s 
Run Code Online (Sandbox Code Playgroud)

如果您担心它会在午夜时分破坏,请在此程序中添加一个特殊情况:)

  • 这使我想起.如果您在睡眠期间需要CPU时间,则绝对不应使用此方法.我假设你不要长时间等待远程数据.如果你这样做,你最好使用shell包装器,因为上面的例子是cpu密集型的. (3认同)
  • 它*稍微*更便携,但它正在忙于等待,而不是正常的睡眠,因此,可接受的答案是正确的答案。 (3认同)