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 使用率。
相关推荐
Avalon7125 小时前
Unity3D响应式渲染UI框架UniVue
游戏·ui·unity·c#·游戏引擎
风酥糖6 小时前
Godot游戏练习01-第33节-新增会爆炸的敌人
游戏·游戏引擎·godot
ellis19706 小时前
Unity UI性能优化一之插件【Unity UI Optimization Tool】
unity·性能优化
Zik----9 小时前
Unity基础学习笔记(B站视频课整理)
unity·vr
郑寿昌19 小时前
UE5与UE6在Lumen和Nanite的差异解析
游戏引擎·图形渲染·着色器
郝学胜-神的一滴1 天前
罗德里格斯旋转公式(Rodrigues‘ Rotation Formula)完整推导
c++·unity·godot·图形渲染·three.js·unreal
郑寿昌1 天前
UE6 AI加速Lumen光线追踪降噪技术解析
人工智能·游戏引擎
晴夏。1 天前
GAS下的网络同步的全面分析【超级全面】
游戏引擎·ue·gas·网络同步
田鸡_1 天前
Unity新输入系统(Input System)教学篇
unity·游戏引擎·游戏程序
EQ-雪梨蛋花汤1 天前
【Unity笔记】Unity 音游模板与免费资源:高效构建节奏游戏开发全指南
笔记·unity·游戏引擎