C - 字符串统计 Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u

本文介绍了一种方法,用于统计给定字符串中数字字符的出现次数。通过解析输入的字符串,程序能够准确地计算出所有数字字符的数量。

Description

对于给定的一个字符串,统计其中数字字符出现的次数。
 

Input

输入数据有多行,第一行是一个整数n,表示测试实例的个数,后面跟着n行,每行包括一个由字母和数字组成的字符串。
 

Output

对于每个测试实例,输出该串中数值的个数,每个输出占一行。
 

Sample Input

2 asdfasdf123123asdfasdf asdf111111111asdfasdfasdf
 

Sample Output

6 9
 


#include<stdio.h>

int main()
{
    int n;
    scanf("%d\n",&n);    //输入后面有转行,不仅在输出中,输入中也有。

    char str[10000];      //虽然不知道字符串的长度,但是不用动态开辟。!!n在编译的时候并没有赋值,不能作为数组下标

    while(n--)
    {
        int i=0,counts=0;
        gets(str);
        while(str[i]!='\0')    //字符串结束的表示系统自动带0
        {
            if((str[i]<='9')&&(str[i]>='0'))
                counts++;
            i++;
        }
        printf("%d\n",counts);


    }
    return 0;


}
import os import sys import io import socket import time import re import threading import tkinter as tk import ttkbootstrap as tb from ttkbootstrap.constants import * from PIL import Image, ImageTk, ImageDraw import psutil import math import random # ====================== 数据采集服务 ====================== class HardwareMonitorService: def __init__(self): self.config = self.read_config() if self.config is None: raise Exception(&quot;配置读取失败,无法启动服务&quot;) self.server_ip = self.config.get(&#39;SERVER_IP&#39;) self.server_port = int(self.config.get(&#39;SERVER_PORT&#39;)) self.client_ip = self.config.get(&#39;CLIENT_IP&#39;) self.client_port = int(self.config.get(&#39;CLIENT_PORT&#39;)) self.running = True self.sock = None self.send_count = 1 self.setup_socket() # 启动服务线程 self.service_thread = threading.Thread(target=self.run_service, daemon=True) self.service_thread.start() def read_config(self): config = {} try: with open(&#39;config.txt&#39;, &#39;r&#39;) as config_file: for line in config_file: if &#39;=&#39; in line: key, value = line.strip().split(&#39;=&#39;, 1) config[key] = value print(&quot;读取配置成功&quot;, flush=True) return config except FileNotFoundError: print(&quot;无法打开配置文件!&quot;, flush=True) return None def is_command_available(self, command): &quot;&quot;&quot;检查命令是否可用&quot;&quot;&quot; if os.name == &#39;nt&#39;: # Windows 系统 result = os.system(f&#39;where {command} &gt;nul 2&gt;&amp;1&#39;) else: # Linux 系统 result = os.system(f&#39;which {command} &gt;/dev/null 2&gt;&amp;1&#39;) return result == 0 def get_hardware_info(self, send_count): # 执行 cnmon info -e 命令并捕获输出 with os.popen(&#39;cnmon info -e&#39;) as f: result_temp = f.read() temperature_lines = self.extract_info(result_temp, &quot;Temperature&quot;, &quot;QDD Status&quot;) # 执行 cnmon info -p 命令并捕获输出 with os.popen(&#39;cnmon info -p&#39;) as f: result_power = f.read() power_lines = self.extract_info(result_power, &quot;Power&quot;, &quot;QDD Status&quot;) # 执行 cnmon info -m 命令并捕获输出 with os.popen(&#39;cnmon info -m&#39;) as f: result_memory = f.read() memory_lines = self.extract_info(result_memory, &quot;v4.9.5&quot;, &quot;Virtual Memory Usage&quot;) # 执行 cnmon info -b 命令并捕获输出 with os.popen(&#39;cnmon info -b&#39;) as f: result_bandwidth = f.read() bandwidth_lines = self.extract_info(result_bandwidth, &quot;QDD 7 : Invalid&quot;, &quot; Chassis&quot;) # 执行 cnmon info -u 命令并捕获输出 with os.popen(&#39;cnmon info -u&#39;) as f: result_usage = f.read() usage_lines = self.extract_info(result_usage, &quot;Utilization&quot;, &quot;QDD Status&quot;) usage_str = &#39;\n&#39;.join(usage_lines) mlu_average = 0 mlu_0 = 0 mlu_1 = 0 mlu_2 = 0 mlu_3 = 0 cpu_chip = 0 cpu_core_0 = 0 cpu_core_1 = 0 cpu_core_2 = 0 cpu_core_3 = 0 # 提取 MLU 平均利用率 mlu_avg_match = re.search(r&#39;MLU Average\s+:\s+(\d+) %&#39;, usage_str) if mlu_avg_match: mlu_average = float(mlu_avg_match.group(1)) # 提取 MLU 0 - 3 利用率 mlu_0_3_match = re.search(r&#39;MLU 0-3\s+:\s+(\d+) %\s+(\d+) %\s+(\d+) %\s+(\d+) %&#39;, usage_str) if mlu_0_3_match: mlu_0 = float(mlu_0_3_match.group(1)) mlu_1 = float(mlu_0_3_match.group(2)) mlu_2 = float(mlu_0_3_match.group(3)) mlu_3 = float(mlu_0_3_match.group(4)) # 提取 CPU 芯片利用率 cpu_chip_match = re.search(r&#39;Device CPU Chip\s+:\s+(\d+) %&#39;, usage_str) if cpu_chip_match: cpu_chip = float(cpu_chip_match.group(1)) # 提取 CPU 核心 0 - 3 利用率 cpu_core_0_3_match = re.search(r&#39;Device CPU Core 0-3\s+:\s+(\d+) %\s+(\d+) %\s+(\d+) %\s+(\d+) %&#39;, usage_str) if cpu_core_0_3_match: cpu_core_0 = float(cpu_core_0_3_match.group(1)) cpu_core_1 = float(cpu_core_0_3_match.group(2)) cpu_core_2 = float(cpu_core_0_3_match.group(3)) cpu_core_3 = float(cpu_core_0_3_match.group(4)) # 添加分隔符和发送次数 info_str = ( &quot;温度信息:\n{}\n\n功率信息:\n{}\n\n内存信息:\n{}\n\n带宽信息:\n{}\n\nMLU信息:\nMLU Average: {}%\nMLU 0-3 利用率:\nMLU 0: {}%\nMLU 1: {}%\nMLU 2: {}%\nMLU 3: {}%\n\nCPU信息:\n&quot; &quot;Device CPU Chip: {}%\nCPU核心 0-3 利用率:\nDevice CPU Core 0: {}%\nDevice CPU Core 1: {}%\nDevice CPU Core 2: {}%\nDevice CPU Core 3: {}%\n发送次数:\nsend_count : {}次\n---------------END---------------&quot; ).format( &#39;\n&#39;.join(temperature_lines), &#39;\n&#39;.join(power_lines), &#39;\n&#39;.join(memory_lines), &#39;\n&#39;.join(bandwidth_lines), mlu_average, mlu_0, mlu_1, mlu_2, mlu_3, cpu_chip, cpu_core_0, cpu_core_1, cpu_core_2, cpu_core_3, send_count ) return info_str def extract_info(self, result, start_keyword, end_keyword): &quot;&quot;&quot;提取指定关键字之间的信息&quot;&quot;&quot; lines = result.splitlines() extracted = [] started = False for line in lines: if start_keyword in line: started = True elif started and line.strip(): if end_keyword in line: break extracted.append(line.strip()) return extracted def setup_socket(self): &quot;&quot;&quot;设置UDP套接字&quot;&quot;&quot; try: # 创建 UDP 套接字 self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 端口号快速重用 self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 绑定服务器 IP 和端口 self.sock.bind((self.server_ip, self.server_port)) print(f&quot;绑定到 {self.server_ip}:{self.server_port}&quot;, flush=True) except OSError as e: print(f&quot;绑定错误: {e}&quot;, flush=True) self.running = False def run_service(self): &quot;&quot;&quot;运行数据采集服务&quot;&quot;&quot; print(&quot;硬件监控服务已启动&quot;, flush=True) while self.running: try: if not self.is_command_available(&#39;cnmon&#39;): info = ( &quot;温度信息:\n&quot; &quot;Board : 34 C\n&quot; &quot;Cluster 0 : 36 C\n&quot; &quot;\n&quot; &quot;功率信息:\n&quot; &quot;Usage : 3.44 W\n&quot; &quot;Cap : 15 W\n&quot; &quot; \n&quot; &quot;内存信息:\n&quot; &quot;Physical Memory Usage :\n&quot; &quot;Total : 8192 MiB\n&quot; &quot;Used : 1669 MiB\n&quot; &quot;Free : 6523 MiB\n&quot; &quot;Channel Memory Usage :\n&quot; &quot; 0 : 1669 MiB\n&quot; &quot;DDR Data Widths : 64 bit\n&quot; &quot;DDR BandWidth : 29 GB/s\n&quot; &quot;\n&quot; &quot;带宽信息:\n&quot; &quot;Bandwidth : N/A\n&quot; &quot;\n&quot; &quot;CPU信息:\n&quot; &quot;Device CPU Chip: 6.0%\n&quot; &quot;CPU核心 0-3 利用率:\n&quot; &quot;Device CPU Core 0: 3.0%\n&quot; &quot;Device CPU Core 1: 20.0%\n&quot; &quot;Device CPU Core 2: 9.0%\n&quot; &quot;Device CPU Core 3: 3.0%\n&quot; &quot;\n&quot; &quot;---------------END---------------\n&quot; ) else: info = self.get_hardware_info(self.send_count) # 发送数据到客户端 self.sock.sendto(info.encode(), (self.client_ip, self.client_port)) self.send_count += 1 time.sleep(0.5) except Exception as e: print(f&quot;服务错误: {e}&quot;, flush=True) time.sleep(1) def stop_service(self): &quot;&quot;&quot;停止数据采集服务&quot;&quot;&quot; self.running = False if self.sock: self.sock.close() print(&quot;硬件监控服务已停止&quot;, flush=True) # ====================== GUI 监控界面 ====================== class EnhancedCircularProgressBar: def __init__(self, parent, size=200, thickness=20, bg_color=&quot;#1a1a1a&quot;, fg_color=&quot;#4caf50&quot;, text_color=&quot;#ffffff&quot;, font_size=16, title=&quot;&quot;, unit=&quot;&quot;, max_value=100, glow_effect=True): self.parent = parent self.size = size self.thickness = thickness self.bg_color = bg_color self.fg_color = fg_color self.text_color = text_color self.font_size = font_size self.title = title self.unit = unit self.max_value = max_value self.glow_effect = glow_effect # 创建Canvas self.canvas = tk.Canvas( parent, width=size, height=size, bg=&quot;black&quot;, highlightthickness=0, bd=0 ) # 计算圆心和半径 self.center_x = size / 2 self.center_y = size / 2 self.radius = (size - thickness) / 2 - 5 # 创建渐变效果 self.create_gradient() # 绘制背景圆环 self.draw_background() # 创建进度弧 self.arc_id = self.canvas.create_arc( self.center_x - self.radius, self.center_y - self.radius, self.center_x + self.radius, self.center_y + self.radius, start=90, extent=0, style=tk.ARC, outline=&quot;&quot;, width=thickness, tags=&quot;progress&quot; ) # 创建发光效果 if self.glow_effect: self.glow_id = self.canvas.create_oval( self.center_x - self.radius - 5, self.center_y - self.radius - 5, self.center_x + self.radius + 5, self.center_y + self.radius + 5, outline=&quot;&quot;, fill=&quot;&quot;, tags=&quot;glow&quot; ) # 创建文本元素 self.create_text_elements() # 动画控制变量 self.current_value = 0 self.target_value = 0 self.animation_running = False self.animation_id = None self.last_update_time = time.time() # 性能优化 self.canvas.tag_raise(&quot;progress&quot;) self.canvas.tag_raise(&quot;text&quot;) def create_gradient(self): &quot;&quot;&quot;创建渐变背景效果&quot;&quot;&quot; self.gradient_img = Image.new(&quot;RGBA&quot;, (self.size, self.size), (0, 0, 0, 0)) draw = ImageDraw.Draw(self.gradient_img) for r in range(int(self.radius), 0, -1): alpha = int(150 * (1 - r/self.radius)) draw.ellipse([ self.center_x - r, self.center_y - r, self.center_x + r, self.center_y + r ], outline=(40, 40, 40, alpha)) self.gradient_photo = ImageTk.PhotoImage(self.gradient_img) self.canvas.create_image( self.center_x, self.center_y, image=self.gradient_photo, tags=&quot;background&quot; ) def draw_background(self): &quot;&quot;&quot;绘制背景圆环&quot;&quot;&quot; self.bg_arc_id = self.canvas.create_arc( self.center_x - self.radius, self.center_y - self.radius, self.center_x + self.radius, self.center_y + self.radius, start=0, extent=359.9, style=tk.ARC, outline=self.bg_color, width=self.thickness, tags=&quot;background&quot; ) def create_text_elements(self): &quot;&quot;&quot;创建所有文本元素&quot;&quot;&quot; # 标题文本 self.title_id = self.canvas.create_text( self.center_x, self.center_y - self.radius * 0.5, text=self.title, fill=self.text_color, font=(&quot;Arial&quot;, self.font_size, &quot;bold&quot;), tags=&quot;text&quot; ) # 数值文本 self.value_id = self.canvas.create_text( self.center_x, self.center_y, text=&quot;0&quot;, fill=self.text_color, font=(&quot;Arial&quot;, int(self.font_size * 1.8), &quot;bold&quot;), tags=&quot;text&quot; ) # 单位文本 self.unit_id = self.canvas.create_text( self.center_x, self.center_y + self.radius * 0.3, text=self.unit, fill=self.text_color, font=(&quot;Arial&quot;, self.font_size - 2), tags=&quot;text&quot; ) def calculate_color(self, value): &quot;&quot;&quot;根据数值计算动态颜色&quot;&quot;&quot; ratio = value / self.max_value # 温度特殊处理(红色表示高温) if &quot;温度&quot; in self.title: r = min(255, int(255 * ratio)) g = min(255, int(255 * (1 - ratio))) b = 50 return f&quot;#{r:02x}{g:02x}{b:02x}&quot; # 正常渐变:绿 -&gt; 黄 -&gt; 红 if ratio &lt; 0.5: r = int(255 * ratio * 2) g = 255 else: r = 255 g = int(255 * (1 - (ratio - 0.5) * 2)) return f&quot;#{r:02x}{g:02x}00&quot; def set_value(self, value): &quot;&quot;&quot;设置目标值&quot;&quot;&quot; self.target_value = max(0, min(self.max_value, value)) # 更新数值显示 self.canvas.itemconfig(self.value_id, text=f&quot;{self.target_value:.1f}&quot;) # 启动动画 if not self.animation_running: self.animate() def animate(self): &quot;&quot;&quot;平滑动画更新进度&quot;&quot;&quot; self.animation_running = True # 计算插值(使用缓动函数) delta = self.target_value - self.current_value speed_factor = 0.2 # 控制动画速度 if abs(delta) &gt; 0.1: self.current_value += delta * speed_factor else: self.current_value = self.target_value # 计算弧的角度 angle = 360 * (self.current_value / self.max_value) # 更新弧 self.canvas.itemconfig(self.arc_id, extent=-angle) # 更新颜色 color = self.calculate_color(self.current_value) self.canvas.itemconfig(self.arc_id, outline=color) # 更新发光效果 if self.glow_effect and time.time() - self.last_update_time &gt; 0.1: self.update_glow_effect(color) self.last_update_time = time.time() # 继续动画或停止 if abs(self.current_value - self.target_value) &gt; 0.5: self.animation_id = self.canvas.after(16, self.animate) else: self.current_value = self.target_value self.animation_running = False self.animation_id = None def update_glow_effect(self, color): &quot;&quot;&quot;更新发光效果&quot;&quot;&quot; if not self.glow_effect: return # 创建新的发光图像 glow_img = Image.new(&quot;RGBA&quot;, (self.size, self.size), (0, 0, 0, 0)) draw = ImageDraw.Draw(glow_img) # 解析颜色 r = int(color[1:3], 16) g = int(color[3:5], 16) b = int(color[5:7], 16) # 绘制发光效果 for i in range(1, 6): alpha = int(50 * (1 - i/6)) radius = self.radius + i draw.ellipse([ self.center_x - radius, self.center_y - radius, self.center_x + radius, self.center_y + radius ], outline=(r, g, b, alpha), width=1) self.glow_photo = ImageTk.PhotoImage(glow_img) self.canvas.itemconfig(self.glow_id, image=self.glow_photo) def reset(self): &quot;&quot;&quot;重置进度条&quot;&quot;&quot; if self.animation_id: self.canvas.after_cancel(self.animation_id) self.current_value = 0 self.target_value = 0 self.canvas.itemconfig(self.arc_id, extent=0) self.canvas.itemconfig(self.value_id, text=&quot;0&quot;) color = self.calculate_color(0) self.canvas.itemconfig(self.arc_id, outline=color) class SystemMonitorApp: def __init__(self): # 启动数据采集服务 try: self.monitor_service = HardwareMonitorService() client_ip = self.monitor_service.client_ip client_port = self.monitor_service.client_port except Exception as e: print(f&quot;无法启动数据采集服务: {e}&quot;) self.monitor_service = None client_ip = &quot;127.0.0.1&quot; client_port = 9999 # 创建主窗口 self.root = tb.Window(themename=&quot;darkly&quot;, title=&quot;系统资源监控&quot;, size=(1200, 800)) self.root.iconbitmap(&quot;&quot;) self.root.minsize(1000, 700) # 设置样式 style = tb.Style() style.configure(&quot;TFrame&quot;, background=&quot;#121212&quot;) style.configure(&quot;Title.TLabel&quot;, background=&quot;#121212&quot;, foreground=&quot;#e0e0e0&quot;, font=(&quot;Arial&quot;, 16, &quot;bold&quot;)) # 创建UDP接收套接字 self.udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) try: self.udp_socket.bind((client_ip, client_port)) print(f&quot;GUI绑定到 {client_ip}:{client_port} 接收数据&quot;) except Exception as e: print(f&quot;GUI绑定错误: {e}&quot;) self.udp_socket.settimeout(0.1) # 设置超时避免阻塞 # 存储真实数据的变量 self.real_data = { &quot;cpu_temp&quot;: 0.0, &quot;power&quot;: 0.0, &quot;memory&quot;: 0.0, &quot;bandwidth&quot;: 0.0, &quot;mlu_usage&quot;: 0.0, &quot;cpu_usage&quot;: 0.0 } # 创建主框架 main_frame = tb.Frame(self.root, padding=20) main_frame.pack(fill=tk.BOTH, expand=True) # 标题 tb.Label( main_frame, text=&quot;系统资源实时监控&quot;, style=&quot;Title.TLabel&quot; ).pack(pady=(0, 20)) # 创建进度条容器框架 progress_container = tb.Frame(main_frame) progress_container.pack(fill=tk.BOTH, expand=True, pady=10) # 创建监控指标配置 monitor_config = [ {&quot;title&quot;: &quot;CPU温度&quot;, &quot;unit&quot;: &quot;&deg;C&quot;, &quot;max_value&quot;: 100, &quot;thickness&quot;: 18, &quot;fg_color&quot;: &quot;#ff5555&quot;}, {&quot;title&quot;: &quot;功率&quot;, &quot;unit&quot;: &quot;W&quot;, &quot;max_value&quot;: 200, &quot;thickness&quot;: 18, &quot;fg_color&quot;: &quot;#ffaa00&quot;}, {&quot;title&quot;: &quot;内存使用&quot;, &quot;unit&quot;: &quot;%&quot;, &quot;max_value&quot;: 100, &quot;thickness&quot;: 18, &quot;fg_color&quot;: &quot;#55aaff&quot;}, {&quot;title&quot;: &quot;网络带宽&quot;, &quot;unit&quot;: &quot;Mbps&quot;, &quot;max_value&quot;: 1000, &quot;thickness&quot;: 18, &quot;fg_color&quot;: &quot;#aa55ff&quot;}, {&quot;title&quot;: &quot;MLU利用率&quot;, &quot;unit&quot;: &quot;%&quot;, &quot;max_value&quot;: 100, &quot;thickness&quot;: 18, &quot;fg_color&quot;: &quot;#00cc99&quot;}, {&quot;title&quot;: &quot;CPU利用率&quot;, &quot;unit&quot;: &quot;%&quot;, &quot;max_value&quot;: 100, &quot;thickness&quot;: 18, &quot;fg_color&quot;: &quot;#ff55ff&quot;} ] # 使用网格布局排列进度条 self.progress_bars = [] for i, config in enumerate(monitor_config): frame = tb.Frame(progress_container) frame.grid(row=i//3, column=i%3, padx=20, pady=20, sticky=&quot;nsew&quot;) # 创建增强型进度条 progress_bar = EnhancedCircularProgressBar( frame, size=220, thickness=config[&quot;thickness&quot;], title=config[&quot;title&quot;], unit=config[&quot;unit&quot;], max_value=config[&quot;max_value&quot;], fg_color=config[&quot;fg_color&quot;], glow_effect=True ) self.progress_bars.append(progress_bar) progress_bar.canvas.pack(fill=tk.BOTH, expand=True) # 设置网格列权重 for i in range(3): progress_container.columnconfigure(i, weight=1) for i in range(2): progress_container.rowconfigure(i, weight=1) # 控制面板 control_frame = tb.Frame(main_frame) control_frame.pack(pady=20, fill=tk.X) # 按钮框架 btn_frame = tb.Frame(control_frame) btn_frame.pack(pady=10) tb.Button( btn_frame, text=&quot;启动&quot;, bootstyle=SUCCESS, command=self.start_monitoring ).pack(side=tk.LEFT, padx=5) tb.Button( btn_frame, text=&quot;暂停&quot;, bootstyle=DANGER, command=self.stop_monitoring ).pack(side=tk.LEFT, padx=5) tb.Button( btn_frame, text=&quot;重置&quot;, bootstyle=WARNING, command=self.reset_all ).pack(side=tk.LEFT, padx=5) # 主题选择器 theme_frame = tb.Frame(control_frame) theme_frame.pack(fill=tk.X, pady=10) tb.Label(theme_frame, text=&quot;选择主题:&quot;, bootstyle=PRIMARY).pack(anchor=tk.W) self.theme_var = tk.StringVar(value=&quot;darkly&quot;) themes = [&quot;darkly&quot;, &quot;cyborg&quot;, &quot;solar&quot;, &quot;minty&quot;, &quot;cosmo&quot;, &quot;flatly&quot;] for theme in themes: tb.Radiobutton( theme_frame, text=theme.capitalize(), variable=self.theme_var, value=theme, bootstyle=PRIMARY, command=self.change_theme ).pack(side=tk.LEFT, padx=5) # 状态栏 self.status = tb.Label( self.root, text=&quot;系统准备就绪&quot;, bootstyle=(SECONDARY, INVERSE), anchor=tk.CENTER ) self.status.pack(side=tk.BOTTOM, fill=tk.X) # 监控控制变量 self.monitoring_active = False self.monitoring_thread = None # 启动初始监控 self.start_monitoring() # 窗口关闭事件处理 self.root.protocol(&quot;WM_DELETE_WINDOW&quot;, self.on_close) self.root.mainloop() def start_monitoring(self): &quot;&quot;&quot;启动资源监控&quot;&quot;&quot; if self.monitoring_active: return self.status.config(text=&quot;启动系统资源监控...&quot;) self.monitoring_active = True # 使用线程运行监控,避免阻塞UI self.monitoring_thread = threading.Thread(target=self.monitor_resources, daemon=True) self.monitoring_thread.start() def stop_monitoring(self): &quot;&quot;&quot;停止资源监控&quot;&quot;&quot; self.monitoring_active = False self.status.config(text=&quot;监控已暂停&quot;) def reset_all(self): &quot;&quot;&quot;重置所有监控指标&quot;&quot;&quot; for bar in self.progress_bars: bar.reset() self.status.config(text=&quot;所有监控指标已重置&quot;) def receive_real_data(self): &quot;&quot;&quot;接收并解析真实硬件数据&quot;&quot;&quot; try: data, _ = self.udp_socket.recvfrom(4096) data_str = data.decode(&#39;utf-8&#39;) self.parse_hardware_info(data_str) except socket.timeout: pass # 没有数据是正常的 except Exception as e: print(f&quot;接收数据错误: {e}&quot;) def parse_hardware_info(self, info_str): &quot;&quot;&quot;解析硬件信息字符串&quot;&quot;&quot; try: # 解析CPU温度 temp_match = re.search(r&quot;Board\s+:\s+(\d+\.?\d*)\s*C&quot;, info_str) if temp_match: self.real_data[&quot;cpu_temp&quot;] = float(temp_match.group(1)) # 解析功率 power_match = re.search(r&quot;Usage\s+:\s+(\d+\.?\d*)\s*W&quot;, info_str) if power_match: self.real_data[&quot;power&quot;] = float(power_match.group(1)) # 解析内存使用率 mem_match = re.search(r&quot;Used\s+:\s+(\d+)\s*MiB.*?Total\s+:\s+(\d+)\s*MiB&quot;, info_str, re.DOTALL) if mem_match: used = float(mem_match.group(1)) total = float(mem_match.group(2)) self.real_data[&quot;memory&quot;] = (used / total) * 100 # 解析MLU利用率 mlu_match = re.search(r&quot;MLU Average:\s*(\d+\.?\d*)%&quot;, info_str) if mlu_match: self.real_data[&quot;mlu_usage&quot;] = float(mlu_match.group(1)) # 解析CPU利用率 cpu_match = re.search(r&quot;Device CPU Chip:\s*(\d+\.?\d*)%&quot;, info_str) if cpu_match: self.real_data[&quot;cpu_usage&quot;] = float(cpu_match.group(1)) # 更新状态栏显示 self.status.config(text=f&quot;接收到真实数据: {time.strftime(&#39;%H:%M:%S&#39;)}&quot;) except Exception as e: print(f&quot;解析硬件信息错误: {e}&quot;) def monitor_resources(self): &quot;&quot;&quot;监控系统资源&quot;&quot;&quot; while self.monitoring_active: # 尝试接收真实数据 self.receive_real_data() # 优先使用真实数据,如果没有则使用模拟数据 cpu_temp = self.real_data[&quot;cpu_temp&quot;] or self.get_cpu_temperature() power = self.real_data[&quot;power&quot;] or self.get_power_usage() mem_usage = self.real_data[&quot;memory&quot;] or self.get_memory_usage() network = self.real_data[&quot;bandwidth&quot;] or self.get_network_usage() mlu_usage = self.real_data[&quot;mlu_usage&quot;] or self.get_mlu_usage() cpu_usage = self.real_data[&quot;cpu_usage&quot;] or psutil.cpu_percent() # 更新进度条 self.progress_bars[0].set_value(cpu_temp) # CPU温度 self.progress_bars[1].set_value(power) # 功率 self.progress_bars[2].set_value(mem_usage) # 内存使用 self.progress_bars[3].set_value(network) # 网络带宽 self.progress_bars[4].set_value(mlu_usage) # MLU利用率 self.progress_bars[5].set_value(cpu_usage) # CPU利用率 # 更新状态栏 status_text = ( f&quot;CPU: {cpu_usage:.1f}% | &quot; f&quot;温度: {cpu_temp:.1f}&deg;C | &quot; f&quot;内存: {mem_usage:.1f}% | &quot; f&quot;MLU: {mlu_usage:.1f}%&quot; ) self.status.config(text=status_text) # 控制更新频率 time.sleep(1) def get_cpu_temperature(self): &quot;&quot;&quot;获取CPU温度(模拟)&quot;&quot;&quot; base_temp = 40.0 fluctuation = random.uniform(-2, 8) load_factor = self.progress_bars[5].current_value / 100 * 10 return min(100, max(30, base_temp + fluctuation + load_factor)) def get_power_usage(self): &quot;&quot;&quot;获取功率使用(模拟)&quot;&quot;&quot; base_power = 80.0 fluctuation = random.uniform(-10, 15) load_factor = (self.progress_bars[5].current_value + self.progress_bars[4].current_value) / 200 * 50 return min(200, max(50, base_power + fluctuation + load_factor)) def get_memory_usage(self): &quot;&quot;&quot;获取内存使用率&quot;&quot;&quot; return psutil.virtual_memory().percent def get_network_usage(self): &quot;&quot;&quot;获取网络带宽使用(模拟)&quot;&quot;&quot; base_usage = 300.0 fluctuation = random.uniform(-50, 100) return min(1000, max(0, base_usage + fluctuation)) def get_mlu_usage(self): &quot;&quot;&quot;获取MLU利用率(模拟)&quot;&quot;&quot; base_usage = 30.0 fluctuation = random.uniform(-5, 15) load_factor = random.uniform(0, 40) return min(100, max(0, base_usage + fluctuation + load_factor)) def change_theme(self): &quot;&quot;&quot;更改应用主题&quot;&quot;&quot; theme = self.theme_var.get() tb.Style(theme=theme) self.status.config(text=f&quot;主题已切换为: {theme.capitalize()}&quot;) def on_close(self): &quot;&quot;&quot;窗口关闭时清理资源&quot;&quot;&quot; self.monitoring_active = False if self.monitor_service: self.monitor_service.stop_service() self.udp_socket.close() self.root.destroy() if __name__ == &quot;__main__&quot;: # 设置无缓冲输出 sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding=&#39;utf-8&#39;, line_buffering=True) # 启动GUI应用 SystemMonitorApp()该代码不再使用虚拟测试而是使用MLU220的cnmon指令如;cnmon info -p来获取板卡功耗信息,cnmon info -e来获取板卡温度数据,cnmon info -m来获取板卡内存信息,cnmon info -b来获取板卡带宽信息,cnmon info -u来获取板卡利用率信息。将获取信息方式写入上述代码中
最新发布
06-21
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值