当前位置: 首页 > news >正文

流量监控前端不显示问题

现象描述

前端界面显示上下行速率有问题,明明有流量,有时候是0有时候有数字。

通过接口定位到以下代码:

.h文件

#ifndef __TRAN_MONITOR__ #define __TRANS_MONITOR__ #include "hv/HttpServer.h" int NetSpeedMonitor_Init(const std::string &usbname); hv::Json UpDownloadGet(); #endif

Cpp文件:

#include <iostream> #include <stdio.h> #include <fstream> #include <thread> #include <chrono> #include <sys/stat.h> #include "Comport/TransMonitor.h" #include "hv/hlog.h" #include "hv/HttpServer.h" using namespace std; string upload_speed = "0 bytes/s"; // ❗❗❗❗❗❗❗❗❗❗后台线程不停写,HTTP线程不停读,没有mutex,没有atomic,没有内存屏障 string download_speed = "0 bytes/s"; // ❗❗❗❗❗❗❗❗❗❗导致:读到旧值,空字符串,读到一半的内容 static bool directoryExists(const string& path) { struct stat info; return stat(path.c_str(), &info) == 0 && S_ISDIR(info.st_mode); } static void readNetworkStatistics(const string &usbname) { const string basePath = "/sys/class/net/" + usbname + "/statistics/"; uint64_t prevRxBytes = 0, prevTxBytes = 0; while(true) { if (directoryExists(basePath)) { ifstream rxFile(basePath + "rx_bytes"); ifstream txFile(basePath + "tx_bytes"); uint64_t rxBytes = 0, txBytes = 0; char upspeed[32]; char downspeed[32]; if (rxFile >> rxBytes && txFile >> txBytes) { uint64_t rxDiff = rxBytes - prevRxBytes; // ❗❗❗❗❗❗❗计算的不是速率,只是差值❗❗❗❗❗❗❗❗❗❗ uint64_t txDiff = txBytes - prevTxBytes; //❗❗❗❗❗❗❗第一次diff极大,之后立刻归零❗❗❗❗❗❗❗ string rxUnit = "bytes/s", txUnit = "bytes/s"; double rxValue = rxDiff, txValue = txDiff; if (rxDiff > 1024) { // ❗❗❗❗❗❗❗❗❗❗1.两个 if 都会进l,前面的 KB 计算被后面的 MB 覆盖,逻辑可读性极差,不工程化 rxValue = static_cast<double>(rxDiff) / 1024; rxUnit = "KB/s"; } if (txDiff > 1024) { txValue = static_cast<double>(txDiff) / 1024; txUnit = "KB/s"; } if (rxDiff > 1024 * 1024) { // 2 rxValue = static_cast<double>(rxDiff) / (1024 * 1024); rxUnit = "MB/s"; } if (txDiff > 1024 * 1024) { txValue = static_cast<double>(txDiff) / (1024 * 1024); txUnit = "MB/s"; } if(txValue < 0) txValue = 0; if(rxValue < 0) rxValue = 0; sprintf(upspeed, "%.2f %s", txValue, txUnit.c_str()); sprintf(downspeed, "%.2f %s", rxValue, rxUnit.c_str()); upload_speed = upspeed; download_speed = downspeed; prevRxBytes = rxBytes; prevTxBytes = txBytes; } else { hloge("Read error at network transfer speed"); } rxFile.close(); txFile.close(); } else { sleep(5); } sleep(1); // ❗❗❗❗❗❗❗❗❗❗Linux sleep(1):≥1 秒 } } int NetSpeedMonitor_Init(const std::string &usbname) { thread networkThread(readNetworkStatistics, usbname); networkThread.detach(); return 0; } hv::Json UpDownloadGet() { hv::Json j; j["upstream"] = upload_speed; // ❗❗❗❗❗❗❗❗❗❗后端不建议返回字符串速率 j["downstream"] = download_speed; return j; }

看代码后问题显而易见:

只有在以下条件同时满足时,才会看到非 0:

  • 网卡此刻刚好有流量

  • 线程刚好按近似 1 秒跑

  • HTTP 线程刚好没读到写一半的 string

在demo里能跑,但是在生产环境必出问题。

解决问题

#include <iostream> #include <stdio.h> #include <fstream> #include <thread> #include <chrono> #include <sys/stat.h> #include "Comport/TransMonitor.h" #include "hv/hlog.h" #include "hv/HttpServer.h" #include <atomic> using namespace std; static std::atomic<uint64_t> g_rx_bps{0}; static std::atomic<uint64_t> g_tx_bps{0}; static void readNetworkStatistics(const string& ifname) { const string base = "/sys/class/net/" + ifname + "/statistics/"; uint64_t prevRx = 0, prevTx = 0; auto prevTime = chrono::steady_clock::now(); while (true) { ifstream rx(base + "rx_bytes"); ifstream tx(base + "tx_bytes"); uint64_t rxBytes = 0, txBytes = 0; if (!(rx >> rxBytes && tx >> txBytes)) { sleep(1); continue; } auto now = chrono::steady_clock::now(); double seconds = chrono::duration_cast<chrono::milliseconds>(now - prevTime).count() / 1000.0; if (prevRx != 0 && seconds > 0.2) { g_rx_bps = (rxBytes - prevRx) / seconds; g_tx_bps = (txBytes - prevTx) / seconds; } prevRx = rxBytes; prevTx = txBytes; prevTime = now; sleep(1); } } int NetSpeedMonitor_Init(const std::string &usbname) { thread networkThread(readNetworkStatistics, usbname); networkThread.detach(); return 0; } static std::string formatSpeed(uint64_t bps) { char buf[32]; if (bps < 1024) { snprintf(buf, sizeof(buf), "%lu B/s", bps); } else if (bps < 1024 * 1024) { snprintf(buf, sizeof(buf), "%.2f KB/s", bps / 1024.0); } else { snprintf(buf, sizeof(buf), "%.2f MB/s", bps / (1024.0 * 1024.0)); } return std::string(buf); } hv::Json UpDownloadGet() { uint64_t tx = g_tx_bps.load(); uint64_t rx = g_rx_bps.load(); hv::Json j; j["upstream"] = formatSpeed(tx); j["downstream"] = formatSpeed(rx); return j; }

1.atomic<uint64_t>存速率,避免了 string 竞争,HTTP线程读安全,后台线程安全

static std::atomic<uint64_t> g_rx_bps{0}; static std::atomic<uint64_t> g_tx_bps{0};

2.steady_clock+ 时间差算速率,不依赖sleep(1)精度,线程调度抖动不会把速率压成 0

double seconds = chrono::duration_cast<chrono::milliseconds>(now - prevTime).count() / 1000.0;

3.第一次采样不算速率,避免第一次巨大 diff,避免刚启动速率乱跳

if (prevRx != 0 && seconds > 0.2) {
http://www.cnnetsun.cn/news/88324.html

相关文章:

  • v3基于SpringBoot的酒店管理系统
  • Git安装Windows版本并配置清华镜像用于TensorFlow贡献开发
  • Langchain-Chatchat 0.3.1 Windows本地部署指南
  • 私有云ACK:企业智能化转型的安全基座与算力引擎
  • Docker部署Qwen3-14B及GPU加速实战
  • SWIR相机
  • vLLM 0.11.0 发布:全面移除 V0 引擎,性能与多模态支持再升级
  • 从零开始:使用Git安装TensorRT及其依赖组件
  • 模块十八.集合
  • FLUX.1-dev服装生成LoRA模型体验
  • 使用nexus3搭建自己的制品服务器
  • 38、Linux 邮件与网页浏览实用指南
  • 41、互联网服务实用指南
  • LLaMA-Factory微调与模型中断续训实战
  • GitHub项目实践:Fork并定制你的个性化Anything-LLM前端界面
  • pythonstudy Day37
  • Linly-Talker结合RAG技术实现知识增强型虚拟客服系统
  • 用Deepseek-v3.1在Trae中编写AI中继程序
  • LobeChat能否实现思维导图输出?结构化内容展示尝试
  • 开源5G基站硬件参数
  • C#开发桌面应用调用GPT-SoVITS REST API实战
  • Dify Docker部署与使用全指南
  • 数组作为参数
  • 蜜罐技术-德迅猎鹰
  • Daily Report — Day 9 (Beta)
  • Seed-Coder-8B-Base与SonarQube智能集成路径
  • 基于CentOS7 DM8单机部署配置记录-20251216
  • 大模型入门:预训练、微调和蒸馏,一篇文章全掌握
  • LobeChat能否编写教案?教师备课自动化尝试
  • vLLM-Omni:全模态AI推理框架技术解析