gpt4 book ai didi

docker - 以百分比形式获取 Docker 容器 CPU 使用率

转载 作者:IT老高 更新时间:2023-10-28 12:38:26 41 4
gpt4 key购买 nike

Docker 提供了一个交互式统计命令,docker stats [cid],它提供了有关 CPU 使用率的最新信息,如下所示:

CONTAINER      CPU %          MEM USAGE/LIMIT       MEM %       NET I/O
36e8a65d 0.03% 4.086 MiB/7.798 GiB 0.05% 281.3 MiB/288.3 MiB

我正在尝试以易于理解的格式获取 CPU 使用率的百分比以进行一些分析。

我已经看到/sys/fs 中的统计数据似乎提供了与 Docker Remote API 相似的值这给了我这个 JSON blob:

{
"cpu_usage": {
"usage_in_usermode": 345230000000,
"total_usage": 430576697133,
"percpu_usage": [
112999686856,
106377031910,
113291361597,
97908616770
],
"usage_in_kernelmode": 80670000000
},
"system_cpu_usage": 440576670000000,
"throttling_data": {
"throttled_time": 0,
"periods": 0,
"throttled_periods": 0
}
}

但我不确定如何从中获得准确的 CPU 使用率百分比。

有什么想法吗?

最佳答案

如果你打算使用 Stats API 调用 - 你可以看看 docker 客户端是如何做到的:https://github.com/docker/docker/blob/eb131c5383db8cac633919f82abad86c99bffbe5/cli/command/container/stats_helpers.go#L175-L188

func calculateCPUPercent(previousCPU, previousSystem uint64, v *types.StatsJSON) float64 {
var (
cpuPercent = 0.0
// calculate the change for the cpu usage of the container in between readings
cpuDelta = float64(v.CPUStats.CPUUsage.TotalUsage) - float64(previousCPU)
// calculate the change for the entire system between readings
systemDelta = float64(v.CPUStats.SystemUsage) - float64(previousSystem)
)

if systemDelta > 0.0 && cpuDelta > 0.0 {
cpuPercent = (cpuDelta / systemDelta) * float64(len(v.CPUStats.CPUUsage.PercpuUsage)) * 100.0
}
return cpuPercent
}

基本上,您获取一个引用点,然后查看 10 秒内的差异,然后您可以知道容器使用了多少时间。比如说,我们从容器的 0 SystemCPUUsage 和 0 CPUUsage 开始。如果 10 秒后,我们有 10 个 SystemCPUUsage 和 1 个 CPUUsage,那么我们有 10% 的使用率。在 API 中,您只是以纳秒而不是秒为单位给出结果。实际时间并不重要,重要的是 SystemCPUUsage 的总变化,然后将 CPUUSage 与之比较。

关于docker - 以百分比形式获取 Docker 容器 CPU 使用率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30271942/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com