Sleep in Fortran

后端 未结 3 1312
长情又很酷
长情又很酷 2021-02-12 23:27

Does anyone know of an way to sleep for a given number of milliseconds in Fortran? I do not want to use non-portable system calls so anything intrinsic to Fortran or C librarie

3条回答
  •  梦毁少年i
    2021-02-12 23:52

    You can use Fortran standard intrinsic functions to do this without C binding:

    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
    

    Assuming the executable is slp:

    ~$ time slp 1234
    
    real        0m1.237s
    user        0m1.233s
    sys         0m0.003s 
    

    Add a special case to this program if you are worried it will break around midnight :)

提交回复
热议问题