GNATPro19.0下Ada.Real_Time.Clock返回值异常及恢复Epoch秒数方法问询
本次测试基于VMWare虚拟化平台搭建两台独立虚拟机开展交叉验证,核心信息如下:
基础环境
- 虚拟机1:搭载GNATPro Ada编译器7.3.2版本,调用
Ada.Real_Time.Clock接口可返回自时间纪元(epoch)起始累计的秒数 - 虚拟机2:搭载GNATPro 19.0版本,调用相同接口返回自虚拟机启动时刻累计的秒数
- 两台虚拟机均采用Ada 95开发标准,系统时间配置已核对完全一致
交叉验证结论
为确认返回值差异是否由编译器版本导致,开展跨环境编译测试:
- 使用GNATPro 19.0编译小型测试程序,在搭载旧版编译器的虚拟机上运行,输出结果与新版编译器所在环境的测试结果完全一致
- 使用旧版编译器编译同款测试程序,在新版编译器所在虚拟机上运行,输出结果与旧版环境的测试结果完全一致
- 可确认差异来源于编译器(runtime)版本特性
核心诉求
通过配置或适配调整,使GNATPro 19.0版本环境下的Ada.Real_Time.Clock接口,能够返回自时间纪元起始累计的秒数
验证用测试程序
with Test_Io; with Ada.Real_Time; procedure Time_Test is Current_Real_Time : Ada.Real_Time.Time; Time_Span : Ada.Real_Time.Time_Span; Seconds_Count : Ada.Real_Time.Seconds_Count; begin Current_Real_Time := Ada.Real_Time.Clock; Ada.Real_Time.Split ( T => Current_Real_Time, Sc => Seconds_Count, Ts => Time_Span); Test_Io.Put_Line("TRACE: Seconds_Count = " & Seconds_Count'Img); end Time_Test;
该差异是GNAT Pro runtime的默认实现调整导致:
- GNATPro 7.3.2及更早的POSIX平台runtime,将
Ada.Real_Time.Clock的底层实现绑定到CLOCK_REALTIME(系统实时时钟),返回自Unix epoch的累计秒数。该实现不符合Ada标准中对实时时钟“单调递增、不受系统时间调整影响”的要求。 - GNATPro 19.0及后续版本调整了默认实现,将底层时钟切换为
CLOCK_MONOTONIC(系统启动后单调递增的时钟),符合Ada标准要求,因此出现了返回虚拟机启动后累计秒数的行为。
由于GNAT Pro采用静态链接runtime的编译模式,交叉验证时编译产物会内置对应版本的runtime实现,因此运行环境不会影响最终输出结果,验证结论成立。
方案一:全局调整Ada.Real_Time.Clock的时间源
在链接步骤添加指定参数,将19.0版本runtime的Ada.Real_Time.Clock底层绑定到CLOCK_REALTIME:
链接参数:
-Wl,--defsym=__gnat_rt_clock_id=CLOCK_REALTIME
若编译环境无法识别CLOCK_REALTIME宏,可直接使用其在Linux下的固定值0,参数写为-Wl,--defsym=__gnat_rt_clock_id=0
调整后所有调用Ada.Real_Time.Clock的代码都会返回自epoch起始的累计秒数。
注意:该实现下的时钟会因系统手动改时、NTP时间同步等操作出现回退,不符合Ada实时时钟的规范要求,仅适用于对时钟单调性无要求的场景。
方案二:不修改全局runtime行为,自行实现epoch秒数获取
若需要同时保留Ada.Real_Time.Clock的单调时钟特性,可直接绑定POSIX的clock_gettime接口获取epoch秒数,不受runtime版本默认配置影响,示例实现如下:
- 新增epoch时间获取的封装包:
with Interfaces.C; use Interfaces.C; package Epoch_Time_Util is -- 返回自Unix epoch起始的累计秒数 function Get_Epoch_Seconds return Long_Long_Integer; end Epoch_Time_Util; package body Epoch_Time_Util is -- POSIX timespec 结构体定义 type timespec is record tv_sec : Long_Long_Integer; tv_nsec : Long_Long_Integer; end record with Convention => C; -- 导入POSIX clock_gettime接口 function clock_gettime(clock_id : int; res : access timespec) return int with Import => True, Convention => C, External_Name => "clock_gettime"; function Get_Epoch_Seconds return Long_Long_Integer is ts : aliased timespec; Ret : int; begin -- CLOCK_REALTIME 的固定ID为0 Ret := clock_gettime(0, ts'Access); if Ret /= 0 then raise Program_Error with "获取系统时间失败"; end if; return ts.tv_sec; end Get_Epoch_Seconds; end Epoch_Time_Util;
- 修改原有测试程序,替换
Ada.Real_Time.Clock的调用:
with Test_Io; with Epoch_Time_Util; procedure Time_Test is Epoch_Seconds : Long_Long_Integer; begin Epoch_Seconds := Epoch_Time_Util.Get_Epoch_Seconds; Test_Io.Put_Line("TRACE: Epoch_Seconds = " & Epoch_Seconds'Img); end Time_Test;
该方案的输出结果完全不受GNAT版本的默认runtime配置影响,稳定性更高,且符合Ada标准对Ada.Real_Time.Clock的行为要求,不会影响原有实时逻辑的单调性需求。
内容的提问来源于stack exchange,提问作者Graham D

