【问题标题】:How can I get CPU usage percent with docker.containers.stats?如何使用 docker.containers.stats 获取 CPU 使用百分比?
【发布时间】:2021-04-05 21:20:55
【问题描述】:

代码:

import docker
cli = docker.from_env()
print(cli.containers.get('container1').stats(stream=False)['precpu_stats'])

输出:

{'cpu_usage': {'total_usage': 6121320874, 'percpu_usage': [4662552384, 1458768490], 'usage_in_kernelmode': 970000000, 'usage_in_usermode': 4940000000}, 'system_cpu_usage': 24545140000000, 'online_cpus': 2, 'throttling_data': {'periods': 0, 'throttled_periods': 0, 'throttled_time': 0}}

如何从这些信息中获取 CPU 使用百分比? 我在终端上使用了docker stats 命令,得到了 0.11% 的 CPU 使用率。 但我无法从这些信息中得到那 0.11%。

【问题讨论】:

  • 这能回答你的问题吗? Get Docker Container CPU Usage as Percentage
  • 我计算了值,但我得到了错误的百分比。所以这没有帮助。
  • 我又读了一遍,我意识到我犯了一个错误,它对我帮助很大。谢谢

标签: python-3.x docker


【解决方案1】:

终于找到答案了,路有点长……

import docker
cli = docker.from_env()
print(cli.containers.get('container').stats(stream=False)['cpu_stats'])
print('---------------------------------------------')
print(cli.containers.get('container').stats(stream=False)['precpu_stats'])

输出是:

{
'cpu_usage': 
    {
     'total_usage': 25382985593,
     'percpu_usage': [17829217240, 7553768353],
     'usage_in_kernelmode': 3280000000,
     'usage_in_usermode': 21040000000
    },
'system_cpu_usage': 75406420000000,
'online_cpus': 2,
'throttling_data': 
    {
     'periods': 0,
     'throttled_periods': 0,
     'throttled_time': 0
    }
}
---------------------------------------------
{
'cpu_usage': 
    {
     'total_usage': 25382168431,
     'percpu_usage': [17828400078, 7553768353],
     'usage_in_kernelmode': 3280000000,
     'usage_in_usermode': 21040000000
    },
'system_cpu_usage': 75400410000000,
'online_cpus': 2,
'throttling_data': 
    {
        'periods': 0,
        'throttled_periods': 0,
        'throttled_time': 0
    }
}

现在为了获得百分比,我们必须这样做:

import docker
client = docker.from_env()
stats = client.containers.get('container').stats(stream=False)
UsageDelta = stats['cpu_stats']['cpu_usage']['total_usage'] - stats['precpu_stats']['cpu_usage']['total_usage']
# from informations : UsageDelta = 25382985593 - 25382168431

SystemDelta = stats['cpu_stats']['cpu_usage']['system_cpu_usage'] - stats['precpu_stats']['cpu_usage']['system_cpu_usage']
# from informations : SystemDelta = 75406420000000 - 75400410000000

len_cpu = len(stats['cpu_stats']['cpu_usage']['percpu_usage'])
# from my informations : len_cpu = 2


percentage = (UsageDelta / SystemDelta) * len_cpu * 100
# this is a little big because the result is : 0.02719341098169717

percent = round(percentage, 2)
# now The output is 0.02 and thats the answer.

【讨论】:

  • 截至 2021 年 12 月 15 日(docker-py 5.0.3),您可以通过执行 stats["cpu_stats"]["system_cpu_usage"] 和 stats["precpu_stats"][" 获得 system_cpu_usage system_cpu_usage"]
猜你喜欢
  • 2020-04-27
  • 1970-01-01
  • 1970-01-01
  • 2020-11-27
  • 2011-10-10
  • 2012-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多