Unity 实时 CPU 使用率监控

发布于:2025-07-28 ⋅ 阅读:(14) ⋅ 点赞:(0)

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

前置条件


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

项目设置


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

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

脚本说明


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

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 使用率。


网站公告

今日签到

点亮在社区的每一天
去签到