我想使用 C# 统一获取 CPU 负载和 RAM 负载(如果可能的话还包括 GPU 负载)。我的代码总是说我的 CPU 处于 100% 负载,而我的 RAM 始终有 0MB 可用空间。这是为什么?我该如何解决这个问题?如果可能的话,我怎样才能额外获得 GPU 负载?
我使用了在几个网站上找到的一些东西,并选择了一个不会给我错误的代码,并且只需要很少的调整就可以输出一些东西。唯一的问题是我总是返回 100% CPU 负载和 0MB 可用内存。我检查了任务管理器和值,其中 ~20% 和 2.4 GB 可用。 代码:
using UnityEngine;
using System.Collections;
using System.Diagnostics;
public class LoadMeasure : MonoBehaviour {
//PerformanceCounter cpuCounter;
//PerformanceCounter ramCounter;
System.Diagnostics.PerformanceCounter cpuCounter;
System.Diagnostics.PerformanceCounter ramCounter;
void Start() {
System.Diagnostics.PerformanceCounterCategory.Exists("PerformanceCounter");
cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
}
void Update(){
UnityEngine.Debug.Log("> cpu: "+getCurrentCpuUsage()+"; >ram: "+getAvailableRAM());
}
public string getCurrentCpuUsage(){
return cpuCounter.NextValue()+"%";
}
public string getAvailableRAM(){
return ramCounter.NextValue()+"MB";
}
}
您的代码中似乎存在一些问题,可能会导致值不正确。让我们仔细检查一下并进行必要的更正:
1。性能计数器的初始化: PerformanceCounterCategory.Exists("PerformanceCounter");该行没有任何用途,并且它不会创建计数器类别的实例。你应该删除它。
2。采样率: 性能计数器需要一些时间来收集准确的数据。在当前的实现中,您在初始化计数器后立即调用 NextValue()。这可能会导致读数不准确。您应该在调用 NextValue() 之前引入延迟。
这是代码的更新版本:
using UnityEngine;
using System.Diagnostics;
using System.Threading;
public class LoadMeasure : MonoBehaviour
{
private PerformanceCounter cpuCounter;
private PerformanceCounter ramCounter;
void Start()
{
cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
}
void Update()
{
// Introduce a delay before sampling again
Thread.Sleep(1000);
UnityEngine.Debug.Log("> cpu: " + getCurrentCpuUsage() + "; >ram: " + getAvailableRAM());
}
public string getCurrentCpuUsage()
{
// Call NextValue twice to get a valid reading
cpuCounter.NextValue();
return cpuCounter.NextValue() + "%";
}
public string getAvailableRAM()
{
return ramCounter.NextValue() + "MB";
}
}
此代码在记录 CPU 和 RAM 使用情况之前引入了 1000 毫秒(1 秒)的延迟。此外,为 CPU 计数器调用 NextValue() 两次有助于获得更准确的读数。
请记住,由于 Unity 的工作方式和现代处理器的多线程特性,在 Unity 中准确测量 CPU 使用率可能具有挑战性。这些值可能不像您预期的那么精确,您应该使用专用的分析工具以获得更准确的结果。