python调用top获取资源使用情况

1、测试需求来源:

基于某服务上线后,随着服务量的增加,此服务资源消耗对系统其他模块产生了相应的影响,针对此服务中占用资源较大的任务开展性能测试,并对性能结果数据进行分析,找出此服务的性能瓶颈,优化线上系统性能质量。

2、测试范围包括:

主要关注进程对cpu、内存及磁盘I/O的消耗情况及任务耗时(基于业务)

3、性能指标:

CPU消耗小于1核,内存消耗小于1G

4、测试场景设计:

基于当前线下测试环境,构造当前线上1倍业务使用量、10倍业务使用量及100倍业务使用量(根据业务规划)

5、测试脚本开发

所需知识点:python调用top命令,获取cpu及内存使用率
linux系统下使用命令:

top -bi >topHistory.log`

可以将top命令打印的文本重定向到日志文件中,以便查看和分析;

top -bi -n 1
top -bi -n 2

6、脚本如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = '...'
__author__ = '...'
__mtime__ = '2019/10/12'
"""
import os
import time
import logging

#使用logging打印出结果
logging.basicConfig(format='%(asctime)s--%(filename)s[line:%(lineno)d]--%(levelname)s: %(message)s',
                    level=logging.DEBUG, filename='parserTopMetric.log', filemode='a')

def parseTop(pid_name):
    while True:
        text = os.popen('top -bi -n 2 -d 0.02').read().split('\n\n')
        mem_text = text[0].split('\n')[3]#获取KiB Mem 的值 ---->KiB Mem :6384865+total, 12354860+free, 18582268 used, 12171778+buff/cache
        swap_text = text[0].split('\n')[4]#获取交换内存的值
        pid_text = text[1].split('\n')
        logging.info("当前内存使用情况为:%s" % mem_text)
        logging.info("当前交换内存使用情况为:%s" % swap_text)
        for i in range(len(pid_text)):  # type(pid_text[i])--str
            pid_text[i] = [p for p in pid_text[i].split(' ') if p]
            if pid_text[i][-1] == pid_name:  # 被监控的进程名
                target_pid = pid_text[i]
                cpu_index = target_pid[-4]  # 获取被监控进程的cpu使用率
                mem_index = target_pid[-3]  # 获取被监控进程的内存使用率
        return float(cpu_index), float(mem_index)

# 获取150s内的cpu及内存使用率的最大值
def max_index():
    cpu_data = []
    mem_data = []
    for i in range(30):
        cpu_index, mem_index = parseTop(top)
        cpu_data.append(cpu_index)
        mem_data.append(mem_index)
        time.sleep(5)
    print(cpu_data, mem_data)
    return max(cpu_data), max(mem_data)


# 获取150s内的cpu及内存使用率的平均值
def average_index():
    cpu_data = []
    mem_data = []
    for i in range(30):
        cpu_index, mem_index = parseTop(top)
        cpu_data.append(cpu_index)
        mem_data.append(mem_index)
        time.sleep(5)
    print(cpu_data, mem_data)
    ave_cpu = sum(cpu_data) / len(cpu_data)
    ave_mem = sum(mem_data) / len(mem_data)
    return ave_cpu, ave_mem


if __name__ == '__main__':
	process="XXX"
    max_cpu, max_mem = max_index()
    ave_cpu, ave_mem = average_index()
    logging.info("监控进程%s的cpu使用率的最大值为:%.2f" % process ,% max_cpu)
    logging.info("监控进程%s的内存使用率的最大值为:%.2f" % process,% max_mem)
    logging.info("监控进程%s的cpu使用率的平均值为:%.2f" % process,% ave_cpu)
    logging.info("监控进程%s的cpu使用率的最大值为:%.2f" % process,% ave_mem)

猜你喜欢

转载自blog.csdn.net/ccccsy99/article/details/102938744
今日推荐