本人今日脑瓜一热,忽然想在游戏中制作一个能检测当前电脑CPU占用率的功能。
ps:我知道这听起来很蠢,所以请不要在为什么要这么做这一点上浪费时间了。
首先我引用了几个必要的库:
using UnityEngine;
using System.Collections;
using System.Text;
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
然后运行环境设置为.net2.0,然后用如下代码申请了一个全局的CPU监视器类
PerformanceCounter pc = new PerformanceCounter("Processor", "% Processor Time", "_Total");
调用PerformanceCounter类中的nextvalue函数获得cpu占用率值并输出到unity控制台:
private void PerformanceCounterFun()
{
cpuLoad = pc.NextValue();
UnityEngine.Debug.Log("CPU load = " + cpuLoad + " %.");
UnityEngine.Debug.Log(pc.NextValue());
}
然后设置其每隔1.5秒执行一次:
IEnumerator startCount(){
while (true)
{
yield return new WaitForSeconds(1.5f);
PerformanceCounterFun();
}
}
然而实际运行起来后发现,除了第一次计数是0以外,后面的cpu占用率计数值始终为100,而资源管理器中的显示数值仅有不到20%。。。我脱离unity用同样的api建立一个C#控制台应用程序来做同样的功能,在控制台里能够输出较准确的值,因此API本身应该是没错的。我现在十分好奇为何在UNITY中我会一直得到100这个值。。。。。
本人小白,求大神讲解。。。。。
ps:我知道这听起来很蠢,所以请不要在为什么要这么做这一点上浪费时间了。
首先我引用了几个必要的库:
using UnityEngine;
using System.Collections;
using System.Text;
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
然后运行环境设置为.net2.0,然后用如下代码申请了一个全局的CPU监视器类
PerformanceCounter pc = new PerformanceCounter("Processor", "% Processor Time", "_Total");
调用PerformanceCounter类中的nextvalue函数获得cpu占用率值并输出到unity控制台:
private void PerformanceCounterFun()
{
cpuLoad = pc.NextValue();
UnityEngine.Debug.Log("CPU load = " + cpuLoad + " %.");
UnityEngine.Debug.Log(pc.NextValue());
}
然后设置其每隔1.5秒执行一次:
IEnumerator startCount(){
while (true)
{
yield return new WaitForSeconds(1.5f);
PerformanceCounterFun();
}
}
然而实际运行起来后发现,除了第一次计数是0以外,后面的cpu占用率计数值始终为100,而资源管理器中的显示数值仅有不到20%。。。我脱离unity用同样的api建立一个C#控制台应用程序来做同样的功能,在控制台里能够输出较准确的值,因此API本身应该是没错的。我现在十分好奇为何在UNITY中我会一直得到100这个值。。。。。
本人小白,求大神讲解。。。。。