"““模拟 NTP 时钟同步算法:通过四个时间戳估算网络延时与时钟偏移””" import random def ntp_sync_once(send_instant, client_offset, d1, d2): "““执行一次 NTP 报文交换,返回估算延时与偏移。””“ t1 = send_instant + client_offset # 客户端发送时刻(本地时钟) t2 = send_instant + d1 # 服务端接收时刻(服务端时钟) t3 = send_instant + d1 # 服务端发送时刻(服务端时钟) t4 = send_instant + d1 + d2 + client_offset # 客户端接收时刻(本地时钟) delay = ((t2 - t1) + (t4 - t3)) / 2.0 offset = ((t2 - t1) - (t4 - t3)) / 2.0 return delay, offset, t4 def main(): send_instant = 1000.0 # 报文发送时刻的真实秒数 client_offset = 5.0 # 客户端本地钟比真实时间快 5 秒 avg_delay = 0.05 # 平均网络延迟 50 毫秒 print(“=== NTP 时钟同步模拟 ===”) print(“同步前:客户端本地时间 = %.2f 秒(真实时间 %.2f 秒)” % (send_instant + client_offset, send_instant)) # 正反向网络延迟存在微小不对称,模拟真实网络抖动 d1 = random.uniform(avg_delay 0.8, avg_delay 1.2) d2 = random.uniform(avg_delay 0.8, avg_delay 1.2) delay, offset, t4 = ntp_sync_once(send_instant, client_offset, d1, d2) print(“正向延迟 = %.4f 秒,反向延迟 = %.4f 秒” % (d1, d2)) print(“估算网络往返延时 = %.4f 秒” % delay) print(“估算时钟偏移 = %.4f 秒” % offset) # 标准 NTP 校准:接收时刻的本地时间加上估算偏移 corrected = t4 + offset real_time = send_instant + d1 + d2 print(“校准后客户端时间 = %.4f 秒” % corrected) print(“接收时刻真实时间 = %.4f 秒” % real_time) print(“校准后剩余偏差 = %.6f 秒” % abs(corrected - real_time)) if name == ”main": main() ```
代码用途:用 30 行 Python 复现 NTP 核心算法——通过一次报文交换的四个时间戳,估算网络延时与时钟偏移,并展示上下行网络不对称如何影响校准精度。