本文主要是介绍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));}}
}
原文章地址 https://stackoverflow.com/questions/56684306/how-to-read-system-usage-cpu-ram-etc
这篇关于Unity获取CPU占有率的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!