我怎样才能得到CPU使用率百分比与docker.containers.stats?

5vf7fwbs  于 2023-01-20  发布在  Docker
关注(0)|答案(2)|浏览(148)

代码:

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%。

cpjpxq1n

cpjpxq1n1#

最后我得到了答案,它的方式是有点长...

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.
mzaanser

mzaanser2#

https://gist.github.com/mdaum/a80913e9c828d4bad3714a709f49586e这个typescript实现将轮询本地Docker守护进程的container stats端点,并计算每次的利用率。您将看到计算与 Jmeter 板报告的利用率一一对应。

相关问题