# -*- coding: utf-8 -*- r'''从本机测公网延迟 —— 这是真实用户路径。 为什么不在设备上测: 设备上 curl 自己的公网域名,流量要出到 Cloudflare 边缘再经隧道 绕回同一台设备,是"发夹回路",最坏情况。 真实用户(手表/电脑)在别处,路径短得多。 ''' from __future__ import annotations import statistics import sys import time import urllib.error import urllib.request URL = "https://relay.xxmxxs.top/" HEALTH = "https://relay.xxmxxs.top/v1/health" HEADERS = {"User-Agent": "LanRemote/1.4.0"} def measure(url: str, rounds: int) -> list: times = [] for i in range(rounds): req = urllib.request.Request(url, headers=HEADERS) start = time.perf_counter() try: with urllib.request.urlopen(req, timeout=25) as resp: resp.read() if resp.status == 200: times.append(time.perf_counter() - start) except (urllib.error.URLError, OSError, TimeoutError): pass time.sleep(0.4) return times def report(label: str, times: list, rounds: int) -> None: if not times: print(" %s: 全部失败" % label) return print(" %s: 可用 %d/%d" % (label, len(times), rounds)) print(" 平均 %.0f ms 中位 %.0f ms 最快 %.0f ms 最慢 %.0f ms" % (statistics.mean(times) * 1000, statistics.median(times) * 1000, min(times) * 1000, max(times) * 1000)) def main() -> int: print(" 公网真实路径测试(30 次)") print() report("官网首页", measure(URL, 30), 30) print() report("健康接口", measure(HEALTH, 20), 20) return 0 if __name__ == "__main__": sys.exit(main())