Sun Studio 12:Fortran 编程指南

7.7 时间和日期函数

返回日期时间或经过的 CPU 时间的库函数会因系统的不同而不同。

Fortran 库中支持的时间函数列在下表中:

表 7–3 Fortran 时间函数

名称 

功能 

手册页 

time

返回自 1970 年 1 月 1 日以来经过的秒数 

time(3F)

date

以字符串形式返回日期 

date(3F)

fdate

以字符串形式返回当前时间和日期 

fdate(3F)

idate

在整型数组中返回当前的年、月、日 

idate(3F)

itime

在整型数组中返回当前的时、分、秒 

itime(3F)

ctime

time 函数返回的时间转换成字符串

ctime(3F)

ltime

time 函数返回的时间转换成本地时间

ltime(3F)

gmtime

time 函数返回的时间转换成格林威治时间

gmtime(3F)

etime

单处理器:返回程序执行经过的用户及系统时间 多处理器:返回挂钟时间

etime(3F)

dtime

返回自上次调用 dtime 以来经过的用户及系统时间

dtime(3F)

date_and_time

以字符和数字形式返回日期及时间 

date_and_time(3F)

有关详细信息,参见《Fortran 库参考手册 》或这些函数各自的手册页。下面给出了一个使用这些时间函数的简单示例 (TestTim.f):


      subroutine startclock
      common / myclock / mytime
      integer mytime, time
      mytime = time()
      return
      end
      function wallclock()
      integer wallclock
      common / myclock / mytime
      integer mytime, time, newtime
      newtime = time()
      wallclock = newtime–  mytime
      mytime = newtime
      return
      end
      integer wallclock, elapsed
      character*24 greeting
      real dtime, timediff, timearray(2)
c      print a heading
      call fdate( greeting )
      print*,  "      Hello, Time Now Is: ",  greeting
      print*,      "See how long ’sleep 4’ takes, in seconds"
      call startclock
      call system( ’sleep 4’ )
      elapsed = wallclock()
      print*, "Elapsed time for sleep 4 was: ", elapsed," seconds"
c      now test the cpu time for some trivial computing
      timediff = dtime( timearray )
      q = 0.01
      do 30 i = 1, 100000
            q = atan( q )
30      continue
      timediff = dtime( timearray )
      print*, "atan(q) 100000 times took: ", timediff ," seconds"
      end

运行该程序会产生以下结果:


demo% TimeTest
       Hello, Time Now Is: Thu Feb  8 15:33:36 2001
 See how long ’sleep 4’ takes, in seconds
 Elapsed time for sleep 4 was:  4  seconds
 atan(q) 100000 times took:  0.01  seconds
demo%

下表中所列的这些例程提供了与 VMS Fortran 系统例程 idatetime 的兼容性。要使用这些例程,必须在 f95 命令行中加入 -lV77 选项,此时还会得到这些 VMS 版本,而非标准 f95 版本。

表 7–4 汇总:非标准 VMS Fortran 系统例程

名称 

定义 

调用序列 

参数类型 

idate

日期为年、月、日形式 

call idate( d, m, y )

integer

time

当前时间为 hhmmss 形式

call time( t )

character*8


注 –

date(3F) 例程和 VMS 版本的 idate(3F) 存在 2000 年安全问题,因为它们返回包含两位数值的年份。通过减去这些例程返回的日期来计算持续时间的程序,在 1999 年 12 月 31 日之后,其计算结果将是错误的。应改用 Fortran 95 例程 date_and_time(3F)。有关详细信息,参见《Fortran 库参考手册》。