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 使用率,并通过多线程更新实时值,避免主线程阻塞。

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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DaLiangChen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值