资讯动态

从源码到实践:psrecord的工作原理与关键函数实现分析

发布时间:2026/8/14 11:26:04 来源:尧图企业网站定制
从源码到实践psrecord的工作原理与关键函数实现分析【免费下载链接】psrecordRecord the CPU and memory activity of a process :chart_with_upwards_trend:项目地址: https://gitcode.com/gh_mirrors/ps/psrecordpsrecord是一款强大的系统监控工具能够实时记录进程的CPU和内存活动帮助开发者深入了解程序运行时的资源占用情况。本文将从源码角度解析psrecord的核心工作原理并详细分析关键函数的实现逻辑为你提供一份完整的技术指南。一、psrecord的核心功能与架构设计psrecord的核心功能是监控指定进程及其子进程的CPU使用率、内存占用并支持将数据记录到日志文件或生成可视化图表。项目采用模块化设计主要由以下几个部分组成命令行解析模块负责解析用户输入的命令参数如进程ID、监控时长、采样间隔等进程监控模块通过psutil库获取进程的CPU和内存信息数据记录模块将监控数据以纯文本或CSV格式写入日志文件可视化模块使用matplotlib生成CPU和内存使用趋势图1.1 项目目录结构psrecord/ ├── tests/ # 单元测试目录 │ ├── __init__.py │ └── test_main.py ├── __init__.py ├── __main__.py # 程序入口点 └── main.py # 核心功能实现二、关键函数实现深度解析2.1 主函数入口main()main()函数位于psrecord/main.py文件中是psrecord的入口点。它负责解析命令行参数根据用户输入决定是附加到现有进程还是启动新进程并调用monitor()函数开始监控。def main(): parser argparse.ArgumentParser(descriptionRecord CPU and memory usage for a process) # 参数解析逻辑... # 附加到进程或启动新进程 try: pid int(args.process_id_or_command) print(fAttaching to process {pid}) sprocess None except Exception: # 启动新进程的逻辑... monitor( pid, logfileargs.log, plotargs.plot, durationargs.duration, intervalargs.interval, include_childreninclude_children, include_ioargs.include_io, log_formatargs.log_format, )2.2 核心监控函数monitor()monitor()函数是psrecord的核心实现了完整的监控逻辑。它通过psutil库获取进程信息按照指定的时间间隔采样数据并根据用户配置将数据记录到日志或准备绘图。2.2.1 监控循环的实现def monitor( pid, logfileNone, plotNone, durationNone, intervalNone, include_childrenFalse, include_ioFalse, log_formatplain, ): import psutil pr psutil.Process(pid) start_time time.time() # 日志文件初始化... try: # 主监控循环 while True: current_time time.time() elapsed_time current_time - start_time # 检查进程状态 try: pr_status pr.status() except psutil.NoSuchProcess: break # 检查是否达到监控时长 if duration is not None and elapsed_time duration: break # 获取CPU和内存信息 current_cpu get_percent(pr) current_mem get_memory(pr) current_mem_real current_mem.rss / 1024.0**2 current_mem_virtual current_mem.vms / 1024.0**2 # 处理子进程信息如果需要 if include_children: # 累加子进程资源占用... # 写入日志 if logfile: # 日志写入逻辑... # 等待采样间隔 if interval is not None: time.sleep(interval) # 记录绘图数据 if plot: # 数据记录逻辑... except KeyboardInterrupt: pass2.3 进程信息获取函数psrecord通过以下两个函数获取进程的CPU和内存信息def get_percent(process): return process.cpu_percent() def get_memory(process): return process.memory_info()这两个函数封装了psutil库的接口为监控循环提供了统一的数据获取方式。2.4 子进程处理all_children()当用户指定--include-children参数时psrecord会监控目标进程及其所有子进程的资源占用。all_children()函数负责递归获取所有子进程def all_children(pr): global children try: children_of_pr pr.children(recursiveTrue) except Exception: return children for child in children_of_pr: if child not in children: children.append(child) return children2.5 数据可视化实现psrecord使用matplotlib库生成CPU和内存使用趋势图。当指定--plot参数时监控数据会被记录到log字典中监控结束后调用matplotlib绘制图表if plot: import matplotlib.pyplot as plt with plt.rc_context({backend: Agg}): fig plt.figure() ax fig.add_subplot(1, 1, 1) ax.plot(log[times], log[cpu], -, lw1, colorr) ax.set_ylabel(CPU (%), colorr) ax.set_xlabel(time (s)) ax2 ax.twinx() ax2.plot(log[times], log[mem_real], -, lw1, colorb) ax2.set_ylabel(Real Memory (MB), colorb) ax.grid() fig.savefig(plot, bbox_inchestight)下面是一个实际的监控结果示例图展示了进程在60秒内的CPU和内存使用情况三、使用示例与最佳实践3.1 基本使用方法监控指定PID的进程python -m psrecord 1234 --log process.log --plot process.png启动并监控新进程python -m psrecord python my_script.py --duration 60 --interval 13.2 高级参数说明--include-children包含子进程的资源占用统计--include-io记录I/O统计信息读取/写入字节数--log-format csv以CSV格式保存日志便于后续分析--duration 300设置监控时长为300秒3.3 源码扩展建议如果你想扩展psrecord的功能可以考虑以下方向添加网络I/O监控功能通过psutil的net_io_counters()实现实现实时数据导出到InfluxDB或Prometheus等监控系统添加进程线程数和句柄数监控四、总结psrecord通过简洁而强大的设计为开发者提供了进程资源监控的有效工具。其核心实现依赖于psutil库获取系统信息通过模块化的设计实现了命令解析、数据采集、日志记录和可视化等功能。本文深入分析了main()和monitor()等关键函数的实现逻辑希望能帮助你更好地理解psrecord的工作原理并为二次开发提供参考。通过掌握psrecord的源码结构和实现细节你可以更灵活地使用这款工具甚至根据自身需求扩展其功能为程序性能优化和问题诊断提供有力支持。【免费下载链接】psrecordRecord the CPU and memory activity of a process :chart_with_upwards_trend:项目地址: https://gitcode.com/gh_mirrors/ps/psrecord创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价