Unity 实时 CPU 使用率监控

在 Unity 中,我们可以通过获取 CPU 使用率来优化性能,或者为用户提供性能监控的反馈信息。本文将指导你如何在 Unity 中实现一个简单的实时 CPU 使用率监控器。

前置条件


  • Unity3D 2018 或更高版本
  • C# 编程基础

项目设置


首先,你需要在 Unity 项目中创建一个 UI 文本组件(TextMeshProUGUI)来显示 CPU 使用率。

  1. 创建一个空的 GameObject,将 CpuUsage 脚本挂载到该 GameObject 上。
  2. 在该 GameObject 上添加一个 TextMeshProUGUI 组件,用来显示 CPU 使用率。

脚本说明


下面是 CpuUsage 脚本的代码实现,代码中使用了 System.Diagnostics 来获取 CPU 使用率,并通过多线程更新实时值,避免主线程阻塞。

cs 复制代码
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using TMPro;
using UnityEngine;

[RequireComponent(typeof(TextMeshProUGUI))]
public class CpuUsage : MonoBehaviour
{
    private TextMeshProUGUI labelText;

    [SerializeField] private float updateInterval = 1;
    [SerializeField] private int processorCount;
    private float cpuUsage;
    private Thread cpuThread;
    private float lasCpuUsage;

    private void Awake()
    {
        labelText = GetComponent<TextMeshProUGUI>();
    }

    private void Start()
    {
        Application.runInBackground = true;

        labelText.text = "CPU使用率:0 %";

        cpuThread = new Thread(updateCPUUsage)
        {
            IsBackground = true,
            Priority = System.Threading.ThreadPriority.BelowNormal
        };

        cpuThread.Start();
    }

    private void OnValidate()
    {
        processorCount = SystemInfo.processorCount / 2;
    }

    private void OnDestroy()
    {
        cpuThread?.Abort();
    }

    private void Update()
    {
        if (Mathf.Approximately(lasCpuUsage, cpuUsage)) return;
        if (cpuUsage < 0 || cpuUsage > 100) return;
        labelText.text = "CPU使用率:" + cpuUsage.ToString("F1") + " %";
        lasCpuUsage = cpuUsage;
    }

    private void updateCPUUsage()
    {
        var lastCpuTime = new TimeSpan(0);

        while (true)
        {
            var cpuTime = new TimeSpan(0);
            var AllProcesses = Process.GetProcesses();
            cpuTime = AllProcesses.Aggregate(cpuTime, (current, process) => current + process.TotalProcessorTime);
            var newCPUTime = cpuTime - lastCpuTime;
            lastCpuTime = cpuTime;
            cpuUsage = 100f * (float)newCPUTime.TotalSeconds / updateInterval / processorCount;
            Thread.Sleep(Mathf.RoundToInt(updateInterval * 1000));
        }
    }
}

代码解析

  1. 组件依赖与初始化

    • 使用 TextMeshProUGUI 显示 CPU 使用率信息,Awake() 方法获取该组件。
    • OnValidate() 方法会自动计算处理器的数量(我们默认处理器数量的一半来进行显示)。
  2. 实时更新 CPU 使用率

    • Start() 方法中,我们创建了一个后台线程 cpuThread,它会定时更新 CPU 使用率。
    • updateCPUUsage() 方法通过 Process.GetProcesses() 获取系统中所有进程的 CPU 使用时间并计算 CPU 的总使用时间。
  3. UI 更新

    • Update() 方法每帧检查 CPU 使用率是否有变化,如果有变化则更新 UI 显示。
    • cpuUsage 为计算出的 CPU 使用率,labelText.text 用来更新显示在 UI 上的文字。
  4. 多线程处理

    • 使用多线程避免阻塞主线程。cpuThread 是一个后台线程,定时获取 CPU 使用时间。
  5. 清理与停止

    • OnDestroy() 方法中,如果线程仍然存在,将会被终止,避免内存泄漏。

性能与优化

  • updateInterval 控制了 CPU 使用率更新的频率,默认为 1 秒。你可以根据实际需求调整更新间隔。
  • 为了避免频繁更新 UI,可以通过 Mathf.Approximately() 方法比较当前和上次的 CPU 使用率是否相同,避免不必要的 UI 更新。

测试

  1. 挂载脚本到一个 GameObject 上。
  2. 确保你的 UI 上有一个 TextMeshProUGUI 组件。
  3. 运行游戏并观察屏幕上的 CPU 使用率。
相关推荐
郝学胜-神的一滴18 小时前
基于OpenGL封装摄像机类:视图矩阵与透视矩阵的实现
c++·qt·线性代数·矩阵·游戏引擎·图形渲染
EQ-雪梨蛋花汤1 天前
【Unity笔记】Unity 编辑器扩展:打造一个可切换 Config.assets 的顶部菜单插件
unity·编辑器·游戏引擎
SmalBox1 天前
【URP】UnityHLSL顶点片元语义详解
unity·渲染
在路上看风景1 天前
9. Mono项目与Unity的关系
unity
在路上看风景1 天前
1.12 Memory Profiler Package - Summary
unity
SmalBox2 天前
【URP】Unity Shader Tags
unity·渲染
极客柒2 天前
Unity 塔防自用可视化路点寻路编辑器
unity·编辑器·游戏引擎
程序猿多布2 天前
Unity AssetBundle详解
unity·assetbundle
萘柰奈2 天前
Unity学习----【进阶】Addressables(二)--加载资源与打包及更新
学习·unity
lvcoc2 天前
unity 接入火山引擎API,包括即梦AI
windows·unity·ai·火山引擎