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