使用python计算K8s的内存和CPU配额

K8s的内存和CPU配额计算

def add_memory(memory1, memory2):
    # 分离数字和单位
    num1, unit1 = int(memory1[:-2]), memory1[-2:]
    num2, unit2 = int(memory2[:-2]), memory2[-2:]

    # 转换为字节大小
    if unit1 == 'Gi':
        bytes1 = num1 * 1024 * 1024 * 1024
    elif unit1 == 'Mi':
        bytes1 = num1 * 1024 * 1024
    else:
        raise ValueError("Invalid memory unit: " + unit1)

    if unit2 == 'Gi':
        bytes2 = num2 * 1024 * 1024 * 1024
    elif unit2 == 'Mi':
        bytes2 = num2 * 1024 * 1024
    else:
        raise ValueError("Invalid memory unit: " + unit2)

    # 相加得到字节大小
    total_bytes = bytes1 + bytes2

    # 转换为带单位的字符串形式
    if total_bytes >= 1024 * 1024 * 1024:
        total_str = str(round(total_bytes / (1024 * 1024 * 1024), 2)).rstrip('0').rstrip('.') + 'Gi'
    elif total_bytes >= 1024 * 1024:
        total_str = str(round(total_bytes / (1024 * 1024), 2)).rstrip('0').rstrip('.') + 'Mi'
    else:
        total_str = str(total_bytes) + 'B'
    return total_str
def add_cpu(cpu1, cpu2):
    # 判断是否包含单位"m",如果不包含则转换为"m"的形式
    if "m" not in cpu1:
        cpu1 = str(float(cpu1) * 1000) + "m"
    if "m" not in cpu2:
        cpu2 = str(float(cpu2) * 1000) + "m"

    # 提取数字部分并转换为浮点数
    num1 = float(cpu1[:-1])
    num2 = float(cpu2[:-1])

    # 相加得到结果
    total_cpu = num1 + num2

    # 判断单位
    if total_cpu >= 1000:
        total_str = str(round(total_cpu / 1000, 2)).rstrip('0').rstrip('.')
    else:
        total_str = str(round(total_cpu, 2)).rstrip('0').rstrip('.') + 'm'
    return total_str


print(add_memory('300Mi', '1Gi'))
print(add_cpu('300m', '1'))

得到结果

1.29Gi
1.3
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值