2011-08-03 221 views
11

有誰知道在Fortran中給定毫秒級的睡眠方法嗎?我不想使用非便攜式系統調用,因此Fortran或C庫固有的任何內容都將是首選。Fortran睡眠

+0

有一個'sleep'子程序需要幾秒作爲參數,但我不確定它來自哪裏(包裝到C函數?)。它似乎對我的意圖工作正常。我在PC上使用英特爾Fortran編譯器12。 –

+0

我只是碰到了一個Fortran程序,它使用一個(非標準)調用系統(char_arg)來訪問沒有cpu開銷的系統。試用pgf90,ifort和gfortran,都可以。所以,可以做一些類似於調用系統('sleep'// number_of_seconds_string)的函數來獲得睡眠函數。沒有機會與其他編譯器一起測試。 – milancurcic

回答

9

使用的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 
+0

您是否認爲英特爾Fortran內部提供的「睡眠」功能基本上與上面提供的功能相同? –

+0

是的,功能可能是相同的。 gfortran提供了一個類似的子程序。這是一個擴展,可能不是其他編譯器的一部分。 –

+1

嗨,在Linux中我可以使用它,它工作正常。在Windows中,使用MinGW編譯時,它抱怨它無法找到睡眠功能。你知道如何解決這個問題嗎? –

4

您可以使用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 

假設可執行文件是SLP:

~$ time slp 1234 

real  0m1.237s 
user  0m1.233s 
sys   0m0.003s 

一個特例加入這一計劃如果y你擔心它會在午夜時分左右:)

+3

這提醒了我。如果您在睡眠期間需要cpu時間,則絕對不應使用此方法。我假設你不需要長時間等待遠程數據。如果你這樣做,你最好使用shell包裝器,因爲上面的例子是cpu密集型的。 – milancurcic