Unity获取CPU占有率

编程入门 行业动态 更新时间:2024-10-06 22:33:31

Unity获取CPU<a href=https://www.elefans.com/category/jswz/34/1758139.html style=占有率"/>

Unity获取CPU占有率

网上很多都是用PerformanceCounter,但是返回的总是0或者100

我在网上找到一个可行的,分享给大家。

using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using TMPro;
using UnityEngine;public class DebugUIManager : MonoBehaviour
{[Header("Components")][SerializeField] private TMP_Text cpuCounterText;[Header("Settings")][Tooltip("In which interval should the CPU usage be updated?")][SerializeField] private float updateInterval = 1;[Tooltip("The amount of physical CPU cores")][SerializeField] private int processorCount;[Header("Output")]public float CpuUsage;private Thread _cpuThread;private float _lasCpuUsage;private void Start(){Application.runInBackground = true;cpuCounterText.text = "0% CPU";// setup the thread_cpuThread = new Thread(UpdateCPUUsage){IsBackground = true,// we don't want that our measurement thread// steals performancePriority = System.Threading.ThreadPriority.BelowNormal};// start the cpu usage thread_cpuThread.Start();}private void OnValidate(){// We want only the physical cores but usually// this returns the twice as many virtual core count//// if this returns a wrong value for you comment this method out// and set the value manuallyprocessorCount = SystemInfo.processorCount / 2;}private void OnDestroy(){// Just to be sure kill the thread if this object is destroyed_cpuThread?.Abort();}private void Update(){// for more efficiency skip if nothing has changedif (Mathf.Approximately(_lasCpuUsage, CpuUsage)) return;// the first two values will always be "wrong"// until _lastCpuTime is initialized correctly// so simply ignore values that are out of the possible rangeif (CpuUsage < 0 || CpuUsage > 100) return;// I used a float instead of int for the % so use the ToString you like for displaying itcpuCounterText.text = CpuUsage.ToString("F1") + "% CPU";// Update the value of _lasCpuUsage_lasCpuUsage = CpuUsage;}/// <summary>/// Runs in Thread/// </summary>private void UpdateCPUUsage(){var lastCpuTime = new TimeSpan(0);// This is ok since this is executed in a background threadwhile (true){var cpuTime = new TimeSpan(0);// Get a list of all running processes in this PCvar AllProcesses = Process.GetProcesses();// Sum up the total processor time of all running processescpuTime = AllProcesses.Aggregate(cpuTime, (current, process) => current + process.TotalProcessorTime);// get the difference between the total sum of processor times// and the last time we called thisvar newCPUTime = cpuTime - lastCpuTime;// update the value of _lastCpuTimelastCpuTime = cpuTime;// The value we look for is the difference, so the processor time all processes together used// since the last time we called this divided by the time we waited// Then since the performance was optionally spread equally over all physical CPUs// we also divide by the physical CPU countCpuUsage = 100f * (float)newCPUTime.TotalSeconds / updateInterval / processorCount;// Wait for UpdateIntervalThread.Sleep(Mathf.RoundToInt(updateInterval * 1000));}}
}

原文章地址

更多推荐

Unity获取CPU占有率

本文发布于:2024-02-13 09:36:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1758149.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:占有率   Unity   CPU

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!