时延latency

网络通信中的时延解析
本文详细介绍了网络通信中的四种时延类型:发送时延、传播时延、处理时延和排队时延,并通过实例解释了它们的计算方法。发送时延取决于数据帧的大小和发送速率;传播时延与信号在介质中的传播速度和距离有关;处理时延涉及对分组的处理和路由查找;而排队时延则与网络拥塞和路由器处理能力相关。理解这些时延对于优化网络性能至关重要。

时延latency

时延

数据(一个报文或分组,甚至比特)从网络(或链路)的一端传送到另一端所需的时间。它是计算机网络的性能指标之一,网络中的时延包括发送时延(传输时延)、传播时延、处理时延、排队时延。

总时延 = 发送时延 + 传播时延 + 处理时延 + 排队时延

发送时延

发送时延是主机或路由器发送数据帧所需要的时间, 也就是从发送数据帧的第一个比特算起,到该帧的最后一个比特发送完毕所需要的时间。发送时延的计算公式为:

发送时延 = 数据帧长度(bit)/ 发送速率(bit/s)

就比如说一个长度为100MB的数据块,在带宽为1Mbit/s的信道上持续发送,求发送时延。
在这儿,我们首先要知道,100MB的数据块有多少bit?
至于为什么要乘8,希望 你要知道8个比特才等于一个字节。然后计算就可以了。
所以发送时延就是838.9s。时间是有点长。

传播时延

传播时延是电磁波在信道中传播一定的距离需要花费的时间。传播时延的计算公式的:

传播时延 = 信道长度(m)/ 电磁波在信道上的传播速率(m/s)

   发送时延与传播时延有本质上的差别。发送时延发生在机器内部的发送器中(一般是发生在网络适配器中),与传播信道的长度无关。 而传播时延发生在机器外部的传播信道媒体上,与信号的发送速率无关。传播信道长度越长,传播时延就越大。

   就比如说,有5辆车按顺序从公路收费站入口出发到相距50公里的目的地,然后咱们就假定每一辆车过收费站要4秒,车速都是每小时100公里。现在就可以算出5辆车都到达目的地所需要的时间:出发时间需要20秒(相当于发送时延),在公路上要滴滴贝贝30分钟(相当于传播时延),因此花费的时间是两者之和30分钟20秒。当然当然当然当然,出发前还可能买买水,排排队什么的也就相当于下面要出场的处理时延和排队时延。

处理时延

主机或路由器在收到分组时要花费一定的时间进行处理,例如分析分组的首部、从分组中提取数据部分、进行差错检验或查找适当的路由等,这就产生了处理时延。

排队时延

分组通过网络传输时,要经过很多路由器。分组在进入路由器后要先在输入队列中排队等待处理。在路由器确定了转发接口后,还要在输出队列中 排队等待转发。这两个因素就造成了排队时延 。

import os import json from flask import Flask, jsonify, request, render_template from datetime import datetime import logging import glob import time import re app = Flask(__name__) # 配置日志 logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) # 定义基础路径(使用更通用的路径格式) BASE_PATH = r"C:\Users\l30078648\Desktop\250730" # 定义芯片和模型组路径映射 TRACK_PATHS = { "Ascend610Lite": { "rl_nn": os.path.join(BASE_PATH, ".track", "Ascend610Lite", "rl_nn"), "rsc_nn": os.path.join(BASE_PATH, ".track", "Ascend610Lite", "rsc_nn"), "prediction_nn": os.path.join(BASE_PATH, ".track", "Ascend610Lite", "prediction_nn") }, "BS9SX1A": { "rl_nn": os.path.join(BASE_PATH, ".track", "BS9SX1A", "rl_nn"), "rsc_nn": os.path.join(BASE_PATH, ".track", "BS9SX1A", "rsc_nn"), "prediction_nn": os.path.join(BASE_PATH, ".track", "BS9SX1A", "prediction_nn") } } JSON_PATHS = { "Ascend610Lite": { "rl_nn": os.path.join(BASE_PATH, "json", "Ascend610Lite", "rl_nn"), "rsc_nn": os.path.join(BASE_PATH, "json", "Ascend610Lite", "rsc_nn"), "prediction_nn": os.path.join(BASE_PATH, "json", "Ascend610Lite", "prediction_nn") }, "BS9SX1A": { "rl_nn": os.path.join(BASE_PATH, "json", "BS9SX1A", "rl_nn"), "rsc_nn": os.path.join(BASE_PATH, "json", "BS9SX1A", "rsc_nn"), "prediction_nn": os.path.join(BASE_PATH, "json", "BS9SX1A", "prediction_nn") } } def get_prebuild_id_data(chip, group): """从原始路径获取Pre Build ID数据(优化版本)""" prebuild_data = {} # 检查路径有效性 if chip not in TRACK_PATHS or group not in TRACK_PATHS[chip]: logger.error(f"无效路径: {chip}/{group}") return prebuild_data group_path = TRACK_PATHS[chip][group] if not os.path.exists(group_path): logger.error(f"原始路径不存在: {group_path}") return prebuild_data # 查找并处理JSON文件 json_files = glob.glob(os.path.join(group_path, "*.json")) for json_file in json_files: try: with open(json_file, 'r') as f: data = json.load(f) model_name = os.path.splitext(os.path.basename(json_file))[0] prebuild_id = data.get('prebuild_id') # 验证prebuild_id格式 if prebuild_id and re.match(r'^[a-f0-9]{32}$', prebuild_id): prebuild_data[model_name] = prebuild_id else: logger.warning(f"无效prebuild_id格式: {prebuild_id} in {json_file}") except Exception as e: logger.error(f"解析原始文件 {json_file} 时出错: {str(e)}") return prebuild_data def extract_quantization_rate(data): """从JSON数据中提取量化率(支持多种键名)""" # 尝试多种可能的键名 keys_to_try = [ 'quantization_rate', 'quantization rate', 'quant_rate', 'quantization_ratio', 'quantization_ratio' ] for key in keys_to_try: if key in data: return data[key] # 尝试嵌套结构 for value in data.values(): if isinstance(value, dict): for nested_key in keys_to_try: if nested_key in value: return value[nested_key] return None def parse_json_file(file_path): """解析新路径的JSON文件,提取性能数据(增强版)""" try: with open(file_path, 'r', encoding='utf-8') as f: data = json.load(f) except Exception as e: logger.error(f"读取文件出错 {file_path}: {e}") return None model_name = os.path.splitext(os.path.basename(file_path))[0] # 提取时延 latency = None for key in data: if key.endswith('.om'): latency = data[key] break # 提取带宽 bandwidth = None if 'mean_ddr' in data: bandwidth = data['mean_ddr'] else: for key, value in data.items(): if isinstance(value, dict) and 'mean_ddr' in value: bandwidth = value['mean_ddr'] break # 提取量化率 quantization_rate = extract_quantization_rate(data) # 获取最后修改时间 last_modified = datetime.fromtimestamp(os.path.getmtime(file_path)).isoformat() return { "model_name": model_name, "latency": latency, "bandwidth": bandwidth, "quantization_rate": quantization_rate, "last_modified": last_modified } def get_performance_data(chip, group): """获取性能数据(优化版本)""" # 创建响应数据结构 performance_data = { "status": "success", "models": [], "timestamp": datetime.now().isoformat(), "chip_type": chip, "group": group, "json_path": JSON_PATHS[chip].get(group, "") if chip in JSON_PATHS else "", "track_path": TRACK_PATHS[chip].get(group, "") if chip in TRACK_PATHS else "", "file_count": 0, "prebuild_id_count": 0 } # 1. 获取Pre Build ID数据 prebuild_id_map = get_prebuild_id_data(chip, group) performance_data["prebuild_id_count"] = len(prebuild_id_map) # 2. 获取性能数据 if chip not in JSON_PATHS or group not in JSON_PATHS[chip]: performance_data["status"] = "error" performance_data["error"] = "无效芯片或模型组" return performance_data group_path = JSON_PATHS[chip][group] if not os.path.exists(group_path): performance_data["status"] = "error" performance_data["error"] = "JSON路径不存在" return performance_data json_files = glob.glob(os.path.join(group_path, "*.json")) performance_data["file_count"] = len(json_files) # 处理每个JSON文件 for json_file in json_files: model_data = parse_json_file(json_file) if model_data: model_name = model_data["model_name"] model_data["prebuild_id"] = prebuild_id_map.get(model_name, "NA") performance_data["models"].append(model_data) return performance_data @app.route('/api/performance', methods=['GET']) def performance_api(): """性能数据API接口(添加缓存控制)""" start_time = time.time() try: device = request.args.get('device', 'Ascend610Lite') group = request.args.get('type', 'rl_nn') logger.info(f"性能API请求 - 设备: {device}, 组: {group}") performance_data = get_performance_data(device, group) process_time = time.time() - start_time # 添加缓存头 response = jsonify({ **performance_data, "process_time": round(process_time, 4) }) response.headers['Cache-Control'] = 'public, max-age=300' # 5分钟缓存 return response except Exception as e: logger.exception("处理请求时出错") return jsonify({ "status": "error", "error": "服务器内部错误", "details": str(e), "process_time": round(time.time() - start_time, 4) }), 500 @app.route('/api/prebuild_ids', methods=['GET']) def prebuild_ids_api(): """专用接口:返回所有prebuild_id(添加分页)""" start_time = time.time() try: device = request.args.get('device', 'Ascend610Lite') group = request.args.get('type', 'rl_nn') page = int(request.args.get('page', 1)) per_page = int(request.args.get('per_page', 50)) logger.info(f"Prebuild ID请求 - 设备: {device}, 组: {group}") prebuild_id_map = get_prebuild_id_data(device, group) all_ids = list(prebuild_id_map.values()) total = len(all_ids) # 分页处理 start_idx = (page - 1) * per_page end_idx = start_idx + per_page paginated_ids = all_ids[start_idx:end_idx] response = { "status": "success", "prebuild_ids": paginated_ids, "page": page, "per_page": per_page, "total": total, "total_pages": (total + per_page - 1) // per_page, "timestamp": datetime.now().isoformat(), "process_time": round(time.time() - start_time, 4) } return jsonify(response) except Exception as e: logger.exception("获取prebuild_id时出错") return jsonify({ "status": "error", "error": "服务器内部错误", "details": str(e), "process_time": round(time.time() - start_time, 4) }), 500 @app.route('/health', methods=['GET']) def health_check(): """健康检查端点(添加更多检查项)""" status = { "status": "ok", "timestamp": datetime.now().isoformat(), "components": { "disk_space": os.path.exists(BASE_PATH), "track_paths": {chip: {group: os.path.exists(path) for group, path in groups.items()} for chip, groups in TRACK_PATHS.items()}, "json_paths": {chip: {group: os.path.exists(path) for group, path in groups.items()} for chip, groups in JSON_PATHS.items()} } } return jsonify(status) @app.route('/debug/paths', methods=['GET']) def debug_paths(): """调试接口:返回路径配置信息(添加文件列表)""" debug_data = { "base_path": BASE_PATH, "track_paths": {}, "json_paths": {} } # 原始路径状态 for chip, group_dict in TRACK_PATHS.items(): debug_data["track_paths"][chip] = {} for group, path in group_dict.items(): exists = os.path.exists(path) entry = { "path": path, "exists": exists } if exists: files = glob.glob(os.path.join(path, "*.json")) entry["file_count"] = len(files) entry["sample_files"] = files[:3] # 显示前3个文件作为示例 debug_data["track_paths"][chip][group] = entry # 新路径状态 for chip, group_dict in JSON_PATHS.items(): debug_data["json_paths"][chip] = {} for group, path in group_dict.items(): exists = os.path.exists(path) entry = { "path": path, "exists": exists } if exists: files = glob.glob(os.path.join(path, "*.json")) entry["file_count"] = len(files) entry["sample_files"] = files[:3] # 显示前3个文件作为示例 debug_data["json_paths"][chip][group] = entry return jsonify(debug_data) @app.route('/') def home(): """首页路由 - 渲染前端页面(添加API文档链接)""" return render_template('index.html') if __name__ == '__main__': # 生产环境建议关闭debug模式 app.run(host="127.0.0.1", port=8080, debug=True) 这个后端脚本提示我的prebuild_id格式无效,解决这个问题
最新发布
08-08
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Erice_s

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值