当前位置: 首页 > news >正文

青岛网站设计建议i青岛博采如何进行网站推广

青岛网站设计建议i青岛博采,如何进行网站推广,小程序商城属于电商吗,学校网站建设设想文章目录 0. 概述1. 数据可视化示例2. 设计思路2.1 系统架构2.2 设计优势 3. 流程图3.1 C录制程序3.2 Python解析脚本 4. 数据结构说明4.1 CpuUsageData 结构体 5. C录制代码解析5.1 主要模块5.2 关键函数5.2.1 CpuUsageMonitor::Run()5.2.2 CpuUsageMonitor::ComputeCpuUsage(… 文章目录 0. 概述1. 数据可视化示例2. 设计思路2.1 系统架构2.2 设计优势 3. 流程图3.1 C录制程序3.2 Python解析脚本 4. 数据结构说明4.1 CpuUsageData 结构体 5. C录制代码解析5.1 主要模块5.2 关键函数5.2.1 CpuUsageMonitor::Run()5.2.2 CpuUsageMonitor::ComputeCpuUsage()5.2.3 CpuUsageMonitor::PrintProcessInfo() 5.3 其他重要功能5.3.1 CpuUsageMonitor::InitializeThreads()5.3.2 CpuUsageMonitor::ReadAndStoreProcessName() 6. Python解析代码解析6.1 主要模块6.2 关键函数6.2.1 parse_cpu_usage_data(record_bytes)6.2.2 read_file_header(f)6.2.3 read_cpu_usage_bin(filename)6.2.4 parse_records_to_dataframe(records, thread_name_map)6.2.5 plot_cpu_usage(...) 0. 概述 本文将介绍一个基于C和Python实现的进程线程CPU使用率监控工具用于监控指定进程及其所有线程的CPU使用情况。 编写这个工具的初衷是源于部分嵌入式ARM系统的top工具不支持显示线程级别的CPU使用情况。 该工具分为两部分 C录制程序负责实时采集指定进程及其线程的CPU使用数据并将数据以二进制格式存储到文件中。 Python解析脚本读取二进制数据文件解析CPU使用数据并生成可视化图表帮助用户直观了解CPU使用情况。 本文完整代码可从gitee的thread-monitor获取到编译和使用方法见README.md 另一种获取CPU使用率的方式使用 Shell 和 Python 解析 top 输出并记录进程及线程的 CPU 使用率 1. 数据可视化示例 以下是生成的CPU使用率图表示例 图中黑色实线表示整个进程的CPU总使用率蓝色实线和虚线分别表示特定线程的用户态和内核态CPU使用率。 本文测试的dummp_worker实现代码见使用C多线程和POSIX库模拟CPU密集型工作 C录制程序终端显示 $ ./thread_cpu_bin -n0.5 dummp_worker -o dump.bin Process Name: dummp_worker Process ID: 19515 Process Priority: 0 Threads (5):Thread Name: dummp_worker, Thread ID: 19515, Priority: 20Thread Name: worker_0, Thread ID: 19516, Priority: -2Thread Name: worker_1, Thread ID: 19517, Priority: -3Thread Name: worker_2, Thread ID: 19518, Priority: -4Thread Name: worker_3, Thread ID: 19519, Priority: -5Python解析脚本终端显示 $ python3 thread_cpu_bin.py dump.bin Process Name: dummp_worker worker_0: Max/Avg User2%/1.01% | Max/Avg Kernel3%/2.03% worker_1: Max/Avg User2%/1.02% | Max/Avg Kernel3%/2.03% worker_2: Max/Avg User2%/1.02% | Max/Avg Kernel3%/2.03% worker_3: Max/Avg User2%/1.02% | Max/Avg Kernel3%/2.03%2. 设计思路 2.1 系统架构 整个系统由两个独立的组件组成 数据采集组件C 监控指定进程的CPU使用情况。定期采集每个线程的用户态和内核态CPU时间。将采集到的数据写入二进制文件便于后续分析。 数据解析与可视化组件Python 读取C采集的二进制数据文件。解析并转换为结构化数据如Pandas DataFrame。计算统计指标最小值、最大值、平均值。生成CPU使用率随时间变化的可视化图表。 2.2 设计优势 高性能使用C进行数据采集确保低延迟和高效性能。灵活性Python脚本提供了灵活的数据处理和可视化能力用户可以根据需要定制分析和展示方式。可扩展性系统设计模块化便于未来功能扩展如添加更多监控指标或支持更多操作系统。 3. 流程图 3.1 C录制程序 #mermaid-svg-Pi2voAHiaypV2GVK {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-Pi2voAHiaypV2GVK .error-icon{fill:#552222;}#mermaid-svg-Pi2voAHiaypV2GVK .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-Pi2voAHiaypV2GVK .edge-thickness-normal{stroke-width:2px;}#mermaid-svg-Pi2voAHiaypV2GVK .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-Pi2voAHiaypV2GVK .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-Pi2voAHiaypV2GVK .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-Pi2voAHiaypV2GVK .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-Pi2voAHiaypV2GVK .marker{fill:#333333;stroke:#333333;}#mermaid-svg-Pi2voAHiaypV2GVK .marker.cross{stroke:#333333;}#mermaid-svg-Pi2voAHiaypV2GVK svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-Pi2voAHiaypV2GVK .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-Pi2voAHiaypV2GVK .cluster-label text{fill:#333;}#mermaid-svg-Pi2voAHiaypV2GVK .cluster-label span{color:#333;}#mermaid-svg-Pi2voAHiaypV2GVK .label text,#mermaid-svg-Pi2voAHiaypV2GVK span{fill:#333;color:#333;}#mermaid-svg-Pi2voAHiaypV2GVK .node rect,#mermaid-svg-Pi2voAHiaypV2GVK .node circle,#mermaid-svg-Pi2voAHiaypV2GVK .node ellipse,#mermaid-svg-Pi2voAHiaypV2GVK .node polygon,#mermaid-svg-Pi2voAHiaypV2GVK .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-Pi2voAHiaypV2GVK .node .label{text-align:center;}#mermaid-svg-Pi2voAHiaypV2GVK .node.clickable{cursor:pointer;}#mermaid-svg-Pi2voAHiaypV2GVK .arrowheadPath{fill:#333333;}#mermaid-svg-Pi2voAHiaypV2GVK .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-Pi2voAHiaypV2GVK .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-Pi2voAHiaypV2GVK .edgeLabel{background-color:#e8e8e8;text-align:center;}#mermaid-svg-Pi2voAHiaypV2GVK .edgeLabel rect{opacity:0.5;background-color:#e8e8e8;fill:#e8e8e8;}#mermaid-svg-Pi2voAHiaypV2GVK .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-Pi2voAHiaypV2GVK .cluster text{fill:#333;}#mermaid-svg-Pi2voAHiaypV2GVK .cluster span{color:#333;}#mermaid-svg-Pi2voAHiaypV2GVK div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-Pi2voAHiaypV2GVK :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 启动程序 初始化线程信息 读取进程名称 写入文件头部信息 进入主循环 采集线程CPU时间 计算CPU使用率 写入CPU使用数据 接收到退出信号 优雅退出 3.2 Python解析脚本 #mermaid-svg-5dq02bbraBWddabo {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-5dq02bbraBWddabo .error-icon{fill:#552222;}#mermaid-svg-5dq02bbraBWddabo .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-5dq02bbraBWddabo .edge-thickness-normal{stroke-width:2px;}#mermaid-svg-5dq02bbraBWddabo .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-5dq02bbraBWddabo .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-5dq02bbraBWddabo .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-5dq02bbraBWddabo .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-5dq02bbraBWddabo .marker{fill:#333333;stroke:#333333;}#mermaid-svg-5dq02bbraBWddabo .marker.cross{stroke:#333333;}#mermaid-svg-5dq02bbraBWddabo svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-5dq02bbraBWddabo .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-5dq02bbraBWddabo .cluster-label text{fill:#333;}#mermaid-svg-5dq02bbraBWddabo .cluster-label span{color:#333;}#mermaid-svg-5dq02bbraBWddabo .label text,#mermaid-svg-5dq02bbraBWddabo span{fill:#333;color:#333;}#mermaid-svg-5dq02bbraBWddabo .node rect,#mermaid-svg-5dq02bbraBWddabo .node circle,#mermaid-svg-5dq02bbraBWddabo .node ellipse,#mermaid-svg-5dq02bbraBWddabo .node polygon,#mermaid-svg-5dq02bbraBWddabo .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-5dq02bbraBWddabo .node .label{text-align:center;}#mermaid-svg-5dq02bbraBWddabo .node.clickable{cursor:pointer;}#mermaid-svg-5dq02bbraBWddabo .arrowheadPath{fill:#333333;}#mermaid-svg-5dq02bbraBWddabo .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-5dq02bbraBWddabo .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-5dq02bbraBWddabo .edgeLabel{background-color:#e8e8e8;text-align:center;}#mermaid-svg-5dq02bbraBWddabo .edgeLabel rect{opacity:0.5;background-color:#e8e8e8;fill:#e8e8e8;}#mermaid-svg-5dq02bbraBWddabo .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-5dq02bbraBWddabo .cluster text{fill:#333;}#mermaid-svg-5dq02bbraBWddabo .cluster span{color:#333;}#mermaid-svg-5dq02bbraBWddabo div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-5dq02bbraBWddabo :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 启动Python脚本 读取二进制文件 解析文件头部信息 解析CPU使用数据 转换为DataFrame 计算统计指标 生成CPU使用率图表 保存并展示图表 4. 数据结构说明 4.1 CpuUsageData 结构体 在C录制程序中定义了一个结构体 CpuUsageData 用于存储每个线程的CPU使用数据。该结构体采用1字节对齐#pragma pack(push, 1)确保数据在二进制文件中的紧凑存储。 #pragma pack(push, 1) struct CpuUsageData {uint8_t user_percent; // 用户态CPU使用百分比 (0-100)uint8_t kernel_percent; // 内核态CPU使用百分比 (0-100)uint16_t user_ticks; // 用户态CPU时间滴答数uint16_t kernel_ticks; // 内核态CPU时间滴答数uint32_t timestamp; // 时间戳自纪元以来的秒数uint32_t thread_id; // 线程ID完整形式uint8_t thread_status; // 线程状态2位uint8_t extra_flags; // 额外标志3位 }; #pragma pack(pop)字段说明 user_percent 和 kernel_percent表示线程在用户态和内核态的CPU使用百分比。user_ticks 和 kernel_ticks表示线程在用户态和内核态的CPU时间滴答数。timestamp记录数据采集的时间点。thread_id线程的唯一标识符。thread_status 和 extra_flags存储线程的状态信息和额外标志位。 5. C录制代码解析 C录制程序负责实时监控指定进程及其线程的CPU使用情况并将数据存储到二进制文件中。以下将详细解析其主要模块和关键函数。 5.1 主要模块 信号处理 通过信号处理机制程序能够优雅地响应用户中断如CtrlC确保资源的正确释放和数据的完整性。 文件和目录管理 使用RAII资源获取即初始化类 FileCloser 和 DirCloser确保文件和目录在使用后自动关闭防止资源泄漏。 线程管理 动态初始化和更新被监控进程的所有线程信息包括线程ID、名称和优先级。 数据采集与记录 定期采集每个线程的CPU使用情况并将数据封装到 CpuUsageData 结构体中。将采集到的数据写入二进制文件中便于后续分析。 5.2 关键函数 5.2.1 CpuUsageMonitor::Run() 程序的主循环负责定期采集数据并记录。 void Run() {GetThreadCpuTicks();current_total_cpu_time_ GetTotalCpuTime();StoreCurrentTicksAsPrevious();while (keep_running) {std::this_thread::sleep_for(std::chrono::durationdouble(refresh_delay_));InitializeThreads();GetThreadCpuTicks();current_total_cpu_time_ GetTotalCpuTime();delta_total_cpu_time_ current_total_cpu_time_ - previous_total_cpu_time_;if (delta_total_cpu_time_ 0) {ComputeCpuUsage();}StoreCurrentTicksAsPrevious();}fprintf(stdout, Exiting gracefully...\n); }功能描述 数据采集调用 GetThreadCpuTicks() 和 GetTotalCpuTime() 获取当前的CPU使用数据。数据处理计算与上次采集之间的CPU时间差并通过 ComputeCpuUsage() 计算CPU使用百分比。数据记录将计算后的数据写入二进制文件。循环控制根据 refresh_delay_ 设置的时间间隔进行循环直到接收到退出信号。 5.2.2 CpuUsageMonitor::ComputeCpuUsage() 计算每个线程的CPU使用百分比并将数据封装为 CpuUsageData 结构体。 void ComputeCpuUsage() {std::lock_guardstd::mutex lck(data_mutex_);auto now std::chrono::system_clock::now();auto epoch now.time_since_epoch();auto seconds_since_epoch std::chrono::duration_caststd::chrono::seconds(epoch).count();uint32_t timestamp static_castuint32_t(seconds_since_epoch);std::vectorCpuUsageData batch_data;for (const auto thread : threads_) {int64_t user_delta 0;int64_t kernel_delta 0;if (previous_ticks_.find(thread) ! previous_ticks_.end()) {user_delta current_ticks_.at(thread).first - previous_ticks_.at(thread).first;kernel_delta current_ticks_.at(thread).second -previous_ticks_.at(thread).second;}uint32_t user_percent 0;uint32_t kernel_percent 0;if (delta_total_cpu_time_ 0) {user_percent static_castuint32_t(static_castdouble(user_delta) /delta_total_cpu_time_ * 100.0);kernel_percent static_castuint32_t(static_castdouble(kernel_delta) / delta_total_cpu_time_ * 100.0);}uint8_t thread_status 0; // e.g., 0 Running, 1 Sleeping, 2 Waiting, 3 Stoppeduint8_t extra_flags 0; // Can store priority or other flagsauto it thread_names_.find(thread);std::string thread_name (it ! thread_names_.end()) ? it-second : unknown;if (thread_name.find(worker) ! std::string::npos) {thread_status 1; // Assume threads with worker in name are sleeping}extra_flags thread_priorities_[thread] 0x7; // Lower 3 bits of priority as extra flagsint real_thread_id std::stoi(thread);CpuUsageData data;data.user_percent user_percent 100 ? 100 : static_castuint8_t(user_percent);data.kernel_percent kernel_percent 100 ? 100 : static_castuint8_t(kernel_percent);data.user_ticks static_castuint16_t(current_ticks_.at(thread).first);data.kernel_ticks static_castuint16_t(current_ticks_.at(thread).second);data.timestamp timestamp;data.thread_id static_castuint32_t(real_thread_id);data.thread_status thread_status;data.extra_flags extra_flags;batch_data.push_back(data);DEBUG_PRINT(Thread ID %u: user_percent%u, kernel_percent%u, status%u, flags%u\n,data.thread_id, data.user_percent, data.kernel_percent,data.thread_status, data.extra_flags);}// Write data to binary fileWriteDataToBinaryFile(batch_data); }功能描述 CPU时间差计算计算当前与上次采集之间的用户态和内核态CPU时间差。CPU使用百分比基于CPU时间差计算每个线程的用户态和内核态CPU使用百分比。状态与标志根据线程名称推断线程状态并提取线程优先级的低3位作为额外标志。数据封装将计算结果封装为 CpuUsageData 结构体并批量写入二进制文件。 5.2.3 CpuUsageMonitor::PrintProcessInfo() 打印进程和所有线程的基本信息包括名称、ID和优先级。 void PrintProcessInfo() {// Lock the mutex to ensure thread-safe access to shared datastd::lock_guardstd::mutex lck(data_mutex_);// Retrieve and print process priorityint process_priority getpriority(PRIO_PROCESS, pid_);if (process_priority -1 errno ! 0) {fprintf(stderr, Failed to get process priority: %s\n, strerror(errno));} else {fprintf(stdout, Process Name: %s\n, process_name_.c_str());fprintf(stdout, Process ID: %d\n, pid_);fprintf(stdout, Process Priority: %d\n, process_priority);}// Print thread informationfprintf(stdout, Threads (%zu):\n, thread_names_.size());for (const auto entry : thread_names_) {// Get thread ID and nameconst std::string thread_id_str entry.first;const std::string thread_name entry.second;// Retrieve thread priorityauto priority_it thread_priorities_.find(thread_id_str);if (priority_it ! thread_priorities_.end()) {int thread_priority priority_it-second;fprintf(stdout, Thread Name: %s, Thread ID: %s, Priority: %d\n,thread_name.c_str(), thread_id_str.c_str(), thread_priority);} else {fprintf(stdout, Thread Name: %s, Thread ID: %s, Priority: Unknown\n,thread_name.c_str(), thread_id_str.c_str());}} }功能描述 进程信息打印输出进程名称、ID和优先级。线程信息打印遍历所有线程输出线程名称、ID和优先级。如果无法获取某个线程的优先级则标记为“Unknown”。 5.3 其他重要功能 5.3.1 CpuUsageMonitor::InitializeThreads() 初始化被监控进程的所有线程信息包括线程ID、名称和优先级。 void InitializeThreads() {std::lock_guardstd::mutex lck(data_mutex_);threads_.clear();thread_names_.clear();thread_priorities_.clear();std::string task_path /proc/ std::to_string(pid_) /task;DIR *dir opendir(task_path.c_str());if (!dir) {fprintf(stderr, Failed to open directory: %s\n, task_path.c_str());return;}DirCloser dir_closer(dir);struct dirent *ent;while ((ent readdir(dir)) ! nullptr) {std::string tid_str ent-d_name;if (std::isdigit(tid_str[0])) {threads_.push_back(tid_str);std::string comm_filename task_path / tid_str /comm;std::ifstream comm_file(comm_filename);if (comm_file.is_open()) {std::string thread_name;if (std::getline(comm_file, thread_name)) {thread_names_[tid_str] thread_name;} else {fprintf(stderr, Failed to read thread name for TID %s\n,tid_str.c_str());thread_names_[tid_str] unknown;}// Get thread priority and nice valuestd::string stat_filename task_path / tid_str /stat;std::ifstream stat_file(stat_filename);if (!stat_file.is_open()) {fprintf(stderr, Failed to open file: %s\n, stat_filename.c_str());continue;}std::string line;if (!std::getline(stat_file, line)) {fprintf(stderr, Failed to read line from file: %s\n,stat_filename.c_str());continue;}std::istringstream iss(line);std::string temp;int priority 0, nice_value 0;// Skip to the priority and nice fieldsfor (int i 0; i PRIORITY_FIELD_INDEX; i) {if (!(iss temp)) {fprintf(stderr, Error parsing stat file: %s\n,stat_filename.c_str());continue;}}// Read priority and nice valueif (!(iss priority nice_value)) {fprintf(stderr,Error parsing priority/nice value from stat file: %s\n,stat_filename.c_str());continue;}// Store prioritythread_priorities_[tid_str] priority;} else {fprintf(stderr, Failed to open comm file for TID %s\n,tid_str.c_str());thread_names_[tid_str] unknown;}}} }功能描述 线程遍历通过访问 /proc/[pid]/task 目录遍历所有线程ID。线程名称获取读取每个线程的 comm 文件获取线程名称。线程优先级获取读取每个线程的 stat 文件解析优先级和nice值。数据存储将线程名称和优先级存储到相应的映射中供后续使用。 5.3.2 CpuUsageMonitor::ReadAndStoreProcessName() 读取被监控进程的名称并存储。 void ReadAndStoreProcessName() {std::string comm_filename /proc/ std::to_string(pid_) /comm;std::ifstream comm_file(comm_filename);if (comm_file.is_open()) {std::getline(comm_file, process_name_);if (!process_name_.empty()) {DEBUG_PRINT(Process name: %s\n, process_name_.c_str());} else {fprintf(stderr, Process name is empty for PID %d.\n, pid_);}} else {fprintf(stderr, Failed to open %s\n, comm_filename.c_str());} }功能描述 进程名称获取通过读取 /proc/[pid]/comm 文件获取进程名称。数据存储将进程名称存储到 process_name_ 变量中以便后续打印和记录。 6. Python解析代码解析 Python脚本负责读取C录制的二进制数据文件解析CPU使用数据并生成可视化图表。以下将详细解析其主要模块和关键函数。 6.1 主要模块 二进制数据解析 读取C程序生成的二进制文件按照预定义的结构体格式解析数据。提取进程名称、线程ID与线程名称的映射。 数据处理与分析 将解析后的数据转换为Pandas DataFrame方便后续分析。计算各线程的CPU使用统计指标最小值、最大值、平均值。 数据可视化 使用Matplotlib生成CPU使用率随时间变化的图表。支持过滤特定线程、CPU使用类型以及时间范围。 6.2 关键函数 6.2.1 parse_cpu_usage_data(record_bytes) 解析单条CPU使用数据。 def parse_cpu_usage_data(record_bytes):Parse a single CpuUsageData record from bytes.Parameters:record_bytes (bytes): 16-byte binary data representing CPU usage.Returns:dict: Parsed fields from the record.if len(record_bytes) ! CPU_USAGE_SIZE:raise ValueError(Record size must be 16 bytes)# Define the struct format: little-endian# B: uint8_t user_percent# B: uint8_t kernel_percent# H: uint16_t user_ticks# H: uint16_t kernel_ticks# I: uint32_t timestamp# I: uint32_t thread_id# B: uint8_t thread_status# B: uint8_t extra_flagsstruct_format BBHHIIBBunpacked_data struct.unpack(struct_format, record_bytes)record {user_percent: unpacked_data[0],kernel_percent: unpacked_data[1],user_ticks: unpacked_data[2],kernel_ticks: unpacked_data[3],timestamp: unpacked_data[4],thread_id: unpacked_data[5],thread_status: unpacked_data[6],extra_flags: unpacked_data[7],}return record功能描述 数据长度校验确保每条记录为16字节。数据解包使用struct.unpack按照C定义的结构体格式解析数据。数据存储将解析后的数据存储到字典中便于后续处理。 6.2.2 read_file_header(f) 读取并解析二进制文件的头部信息。 def read_file_header(f):Read and parse the file header from cpu_usage.bin.Parameters:f (file object): Opened binary file object positioned at the beginning.Returns:tuple: (process_name (str), thread_name_map (dict))# Read header_size (4 bytes)header_size_data f.read(4)if len(header_size_data) 4:raise ValueError(Failed to read header size.)header_size struct.unpack(I, header_size_data)[0]# Read the rest of the headerheader_data f.read(header_size)if len(header_data) header_size:raise ValueError(Failed to read complete header.)offset 0# Read process_name_length (4 bytes)process_name_length struct.unpack_from(I, header_data, offset)[0]offset 4# Read process_nameprocess_name header_data[offset : offset process_name_length].decode(utf-8)offset process_name_length# Read thread_map_size (4 bytes)thread_map_size struct.unpack_from(I, header_data, offset)[0]offset 4thread_name_map {}for _ in range(thread_map_size):# Read thread_id (4 bytes)thread_id struct.unpack_from(I, header_data, offset)[0]offset 4# Read thread_name_length (4 bytes)thread_name_length struct.unpack_from(I, header_data, offset)[0]offset 4# Read thread_namethread_name header_data[offset : offset thread_name_length].decode(utf-8)offset thread_name_lengththread_name_map[thread_id] thread_name# Debug: Print the header information# Uncomment the following lines for debugging purposes# print(fProcess Name: {process_name})# print(fThread Name Map: {thread_name_map})return process_name, thread_name_map功能描述 头部大小读取读取前4字节获取头部大小。进程名称读取根据进程名称长度读取进程名称。线程映射读取读取线程数量及每个线程的ID与名称存储到字典中。 6.2.3 read_cpu_usage_bin(filename) 读取并解析整个二进制数据文件。 def read_cpu_usage_bin(filename):Read and parse the cpu_usage.bin file.Parameters:filename (str): Path to the cpu_usage.bin file.Returns:tuple: (records (list of dict), process_name (str), thread_name_map (dict))records []process_name Unknown Processthread_name_map {}try:with open(filename, rb) as f:# Read and parse the headerprocess_name, thread_name_map read_file_header(f)# Read and parse each CpuUsageData recordwhile True:record_bytes f.read(CPU_USAGE_SIZE)if not record_bytes or len(record_bytes) CPU_USAGE_SIZE:breakrecord parse_cpu_usage_data(record_bytes)records.append(record)except FileNotFoundError:print(fFile {filename} not found.)except Exception as e:print(fError reading binary file: {e})return records, process_name, thread_name_map功能描述 文件读取打开二进制文件并读取头部信息。数据采集循环读取每条CPU使用数据并调用 parse_cpu_usage_data 解析。数据存储将所有记录存储到列表中便于后续转换为DataFrame。 6.2.4 parse_records_to_dataframe(records, thread_name_map) 将解析后的记录转换为Pandas DataFrame。 def parse_records_to_dataframe(records, thread_name_map):Convert parsed records to a pandas DataFrame.Parameters:records (list of dict): Parsed CPU usage records.thread_name_map (dict): Mapping from thread ID to thread name.Returns:pandas.DataFrame: DataFrame containing the CPU usage data.data pd.DataFrame(records)# Ensure thread_id is integerdata[thread_id] data[thread_id].astype(int)# Map thread_id to thread_namedata[thread_name] data[thread_id].map(thread_name_map).fillna(unknown)# Convert timestamp to datetime (assuming timestamp is seconds since epoch)data[timestamp] pd.to_datetime(data[timestamp], units)return data功能描述 数据转换将记录列表转换为Pandas DataFrame。线程名称映射根据线程ID映射线程名称填充“unknown”以处理未知线程。时间戳转换将时间戳转换为可读的日期时间格式。 6.2.5 plot_cpu_usage(...) 生成CPU使用率随时间变化的图表。 def plot_cpu_usage(data,process_nameUnknown Process,filter_threadNone,filter_cpu_typeNone,time_rangeNone,show_summary_infoTrue, ):Plot CPU usage over time for the process and its threads.Parameters:data (pandas.DataFrame): DataFrame containing CPU usage data.process_name (str): Name of the process.filter_thread (str, optional): Filter to include only specific thread names.filter_cpu_type (str, optional): Filter to include only user or kernel CPU usage.time_range (tuple, optional): Tuple of (start_time, end_time) to filter the data.show_summary_info (bool): Whether to display summary information on the plot.plt.figure(figsize(14, 10))# Calculate total CPU usage of the processprocess_cpu calculate_process_cpu(data)# Sort by timestampprocess_cpu process_cpu.sort_values(timestamp)# Plot total CPU usageplt.plot(process_cpu[timestamp],process_cpu[total_usage],labelProcess Total CPU Usage,colorblack,linewidth2,)# Apply filters if anyif filter_thread:data data[data[thread_name].str.contains(filter_thread, caseFalse)]if filter_cpu_type:if filter_cpu_type.lower() user:data data[[timestamp, thread_name, user_percent]]elif filter_cpu_type.lower() kernel:data data[[timestamp, thread_name, kernel_percent]]if time_range:start_time, end_time time_rangedata data[(data[timestamp] start_time) (data[timestamp] end_time)]# Sort data by timestampdata data.sort_values(timestamp)# Set timestamp as index for resamplingdata.set_index(timestamp, inplaceTrue)# Determine resampling frequency based on dataresample_freq S # 1 second# Plot CPU usage for each threadfor thread_name in data[thread_name].unique():subset data[data[thread_name] thread_name]# Resample to ensure continuityuser_usage subset[user_percent].resample(resample_freq).mean().interpolate()kernel_usage subset[kernel_percent].resample(resample_freq).mean().interpolate()# Plot user_percent as solid lineplt.plot(user_usage.index,user_usage.values,labelf{thread_name} (User),linestyle-, # Solid line for user)# Plot kernel_percent as dashed lineplt.plot(kernel_usage.index,kernel_usage.values,labelf{thread_name} (Kernel),linestyle--, # Dashed line for kernel)plt.xlabel(Time)plt.ylabel(CPU Usage (%))plt.title(fCPU Usage Over Time by Thread for Process: {process_name})plt.gcf().autofmt_xdate()plt.legend(locupper left, bbox_to_anchor(1, 1))plt.grid(True)plt.tight_layout(rect[0, 0.1, 1, 0.95])if show_summary_info:summary_info get_summary_table(data.reset_index(), process_name)plt.figtext(0.02,0.01,summary_info,fontsize9,verticalalignmentbottom,horizontalalignmentleft,bboxdict(facecolorwhite, alpha0.5),)try:plt.savefig(cpu_usage_over_time.png)plt.show()except KeyboardInterrupt:print(\nPlotting interrupted by user. Exiting gracefully.)plt.close()sys.exit(0)功能描述 总CPU使用率绘制绘制整个进程的CPU总使用率曲线。线程CPU使用率绘制为每个线程绘制用户态和内核态的CPU使用率曲线其中用户态使用实线内核态使用虚线。过滤与时间范围支持根据线程名称、CPU使用类型和时间范围进行数据过滤。摘要信息在图表底部显示每个线程的CPU使用统计信息。
文章转载自:
http://www.morning.ymfzd.cn.gov.cn.ymfzd.cn
http://www.morning.jpbky.cn.gov.cn.jpbky.cn
http://www.morning.qxnlc.cn.gov.cn.qxnlc.cn
http://www.morning.hnkkf.cn.gov.cn.hnkkf.cn
http://www.morning.jgzmr.cn.gov.cn.jgzmr.cn
http://www.morning.wdrxh.cn.gov.cn.wdrxh.cn
http://www.morning.ghccq.cn.gov.cn.ghccq.cn
http://www.morning.fylqz.cn.gov.cn.fylqz.cn
http://www.morning.wskn.cn.gov.cn.wskn.cn
http://www.morning.bmhc.cn.gov.cn.bmhc.cn
http://www.morning.zdydj.cn.gov.cn.zdydj.cn
http://www.morning.enjoinfo.cn.gov.cn.enjoinfo.cn
http://www.morning.qpqcq.cn.gov.cn.qpqcq.cn
http://www.morning.xqkcs.cn.gov.cn.xqkcs.cn
http://www.morning.brsgw.cn.gov.cn.brsgw.cn
http://www.morning.mzpd.cn.gov.cn.mzpd.cn
http://www.morning.cpqqf.cn.gov.cn.cpqqf.cn
http://www.morning.kqgqy.cn.gov.cn.kqgqy.cn
http://www.morning.qnxtz.cn.gov.cn.qnxtz.cn
http://www.morning.gl-group.cn.gov.cn.gl-group.cn
http://www.morning.sbrxm.cn.gov.cn.sbrxm.cn
http://www.morning.fbqr.cn.gov.cn.fbqr.cn
http://www.morning.fzwf.cn.gov.cn.fzwf.cn
http://www.morning.ykbgs.cn.gov.cn.ykbgs.cn
http://www.morning.xzkgp.cn.gov.cn.xzkgp.cn
http://www.morning.wgxtz.cn.gov.cn.wgxtz.cn
http://www.morning.nrwr.cn.gov.cn.nrwr.cn
http://www.morning.sqnxk.cn.gov.cn.sqnxk.cn
http://www.morning.wschl.cn.gov.cn.wschl.cn
http://www.morning.clbgy.cn.gov.cn.clbgy.cn
http://www.morning.27asw.cn.gov.cn.27asw.cn
http://www.morning.wxccm.cn.gov.cn.wxccm.cn
http://www.morning.xhsxj.cn.gov.cn.xhsxj.cn
http://www.morning.mmjyk.cn.gov.cn.mmjyk.cn
http://www.morning.qwfl.cn.gov.cn.qwfl.cn
http://www.morning.qfmns.cn.gov.cn.qfmns.cn
http://www.morning.kksjr.cn.gov.cn.kksjr.cn
http://www.morning.gfjgq.cn.gov.cn.gfjgq.cn
http://www.morning.nllst.cn.gov.cn.nllst.cn
http://www.morning.ddfp.cn.gov.cn.ddfp.cn
http://www.morning.mdnnz.cn.gov.cn.mdnnz.cn
http://www.morning.litao7.cn.gov.cn.litao7.cn
http://www.morning.gnwpg.cn.gov.cn.gnwpg.cn
http://www.morning.rnpnn.cn.gov.cn.rnpnn.cn
http://www.morning.yhpq.cn.gov.cn.yhpq.cn
http://www.morning.ygrdb.cn.gov.cn.ygrdb.cn
http://www.morning.kynf.cn.gov.cn.kynf.cn
http://www.morning.jzxqj.cn.gov.cn.jzxqj.cn
http://www.morning.cybch.cn.gov.cn.cybch.cn
http://www.morning.gqcd.cn.gov.cn.gqcd.cn
http://www.morning.spqbp.cn.gov.cn.spqbp.cn
http://www.morning.nlysd.cn.gov.cn.nlysd.cn
http://www.morning.zcyxq.cn.gov.cn.zcyxq.cn
http://www.morning.crdtx.cn.gov.cn.crdtx.cn
http://www.morning.mlbn.cn.gov.cn.mlbn.cn
http://www.morning.xwlmr.cn.gov.cn.xwlmr.cn
http://www.morning.zdhnm.cn.gov.cn.zdhnm.cn
http://www.morning.yuanshenglan.com.gov.cn.yuanshenglan.com
http://www.morning.pngdc.cn.gov.cn.pngdc.cn
http://www.morning.cnqdn.cn.gov.cn.cnqdn.cn
http://www.morning.gfmpk.cn.gov.cn.gfmpk.cn
http://www.morning.gzttoyp.com.gov.cn.gzttoyp.com
http://www.morning.zwtp.cn.gov.cn.zwtp.cn
http://www.morning.jglqn.cn.gov.cn.jglqn.cn
http://www.morning.xsrnr.cn.gov.cn.xsrnr.cn
http://www.morning.hjrjr.cn.gov.cn.hjrjr.cn
http://www.morning.ckhpg.cn.gov.cn.ckhpg.cn
http://www.morning.sbjbs.cn.gov.cn.sbjbs.cn
http://www.morning.ttvtv.cn.gov.cn.ttvtv.cn
http://www.morning.crhd.cn.gov.cn.crhd.cn
http://www.morning.lhztj.cn.gov.cn.lhztj.cn
http://www.morning.hnrdtz.com.gov.cn.hnrdtz.com
http://www.morning.wyjhq.cn.gov.cn.wyjhq.cn
http://www.morning.fmrrr.cn.gov.cn.fmrrr.cn
http://www.morning.qjbxt.cn.gov.cn.qjbxt.cn
http://www.morning.vvdifactory.com.gov.cn.vvdifactory.com
http://www.morning.cpgdy.cn.gov.cn.cpgdy.cn
http://www.morning.byywt.cn.gov.cn.byywt.cn
http://www.morning.hxcrd.cn.gov.cn.hxcrd.cn
http://www.morning.jfjfk.cn.gov.cn.jfjfk.cn
http://www.tj-hxxt.cn/news/258105.html

相关文章:

  • 建设银行浙江网站首页商丘网吧
  • 建设公众号网站龙华民治网站设计公司
  • 个人网站免费域名台州黄岩网站建设
  • 进入官方网站陕西住建执业证书官网
  • 个人网站的建设与管理搜索引擎优化师工资
  • 网站建设采购合同验收东莞网站开发方案
  • 定制管理系统软件宁波做网站seo的
  • flash网站链接怎么做软文投放平台有哪些?
  • 如何把网站让百度录用阿里云虚拟主机如何安装wordpress
  • 网站的统计代码seo优缺点
  • 自主网站北京企业建站技术
  • 一个ip地址上可以做几个网站公司注册网上核名通道
  • 公司申请网站建设的工作方案wordpress网页中添加3个音乐播放
  • 网站开发与系统开发做淘宝客要建网站吗
  • 学校网站建设状况做外贸如何访问国外网站
  • 建网站权威机构公司官网建设方案
  • 《两学一做 榜样》网站品牌设计包括哪些设计
  • word里网站的超链接怎么做超便宜的网站
  • 网站免费做招生宣传语wordpress案例讲解
  • 网站加视频播放设计怎么做的模块建站平台
  • 知名网站制作公司建设网站需要多久
  • 网站基本维护网络服务启动失败
  • 宁远县做网站的哪一个做h5的网站好
  • 做h5的网站页面设计临海制作网站公司
  • 网页设计与网站制作上海工商查询网
  • 网站平台建设电子商务营销活动
  • 制作企业网站怎么做站长工具seo综合查询工具
  • 做预算查价格的网站是哪个好可以做简单小活动的网站
  • 东莞网站优化方法有哪些汉川网站推广服务
  • 家用网络建网站网页制作工具分为哪两类