Ai
1 Star 0 Fork 0

junqirao/links-core

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
traffic.go 2.57 KB
一键复制 编辑 原始数据 按行查看 历史
junqirao 提交于 2022-10-15 16:42 +08:00 . feat: 性能监控
package monitor
import (
"encoding/json"
"gitee.com/jackrabbit872568318/links-core/traffic"
"io/ioutil"
"time"
)
//
// TrafficRecorder
// @Description:
//
type TrafficRecorder struct {
old []TrafficStamp
data []TrafficStamp
}
//
// NewTrafficRecorder
// @Description:
// @return TrafficRecorder
//
func NewTrafficRecorder() TrafficRecorder {
return TrafficRecorder{data: make([]TrafficStamp, 0)}
}
//
// Recent
// @Description:
// @receiver r
// @param count
// @return []TrafficStamp
//
func (r *TrafficRecorder) Recent(count int) []TrafficStamp {
arr := make([]TrafficStamp, 0)
currLen := len(r.data)
if currLen < count {
tmp := append(r.old, r.data...)
require := len(tmp) - count
if require < 0 {
require = 0
}
arr = tmp[require:]
} else {
arr = append(arr, r.data[currLen-count:]...)
}
return arr
}
//
// Latest
// @Description:
// @receiver r
// @return []TrafficStamp
//
func (r *TrafficRecorder) Latest() []TrafficStamp {
return r.data
}
//
// Push
// @Description:
// @receiver r
// @param stamp
//
func (r *TrafficRecorder) Push(stamp TrafficStamp) {
r.data = append(r.data, stamp)
}
//
// DumpAndReset
// @Description:
// @receiver r
// @param file
// @return error
//
func (r *TrafficRecorder) DumpAndReset(file string) error {
bytes, err := json.Marshal(r.data)
if err != nil {
return err
}
err = ioutil.WriteFile(file, bytes, 0644)
if err != nil {
return err
}
r.old = make([]TrafficStamp, len(r.data))
copy(r.old, r.data)
r.data = make([]TrafficStamp, 0)
return nil
}
//
// TrafficStamp
// @Description:
//
type TrafficStamp struct {
RxFlow uint64 `json:"rx_flow"` //接收流量
TxFlow uint64 `json:"tx_flow"` //发送流量
RxPacket uint64 `json:"rx_packet"` //数据包接收
TxPacket uint64 `json:"tx_packet"` //数据包发送
Timestamp int64 `json:"timestamp"` //时间戳
}
//
// CreateTrafficStampWithDuration
// @Description:
// @param rx
// @param tx
// @param gap
// @param slice
// @return TrafficStamp
//
func CreateTrafficStampWithDuration(rx, tx *traffic.FlowStatisticsFP, gap int) TrafficStamp {
if rx == nil || tx == nil {
return TrafficStamp{}
}
start := time.Now().UnixMilli()
rxFlowSt1 := rx.Flow
txFlowSt1 := tx.Flow
rxPacketSt1 := rx.Packet
txPacketSt1 := tx.Packet
time.Sleep(time.Millisecond * time.Duration(gap))
rxFlowSt2 := rx.Flow
txFlowSt2 := tx.Flow
rxPacketSt2 := rx.Packet
txPacketSt2 := tx.Packet
return TrafficStamp{
RxFlow: rxFlowSt2 - rxFlowSt1,
TxFlow: txFlowSt2 - txFlowSt1,
RxPacket: rxPacketSt2 - rxPacketSt1,
TxPacket: txPacketSt2 - txPacketSt1,
Timestamp: start,
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/jackrabbit872568318/links-core.git
git@gitee.com:jackrabbit872568318/links-core.git
jackrabbit872568318
links-core
links-core
v0.1.3

搜索帮助