如何在unity制作的游戏中添加一个CPU检测器?

[复制链接]
查看11 | 回复10 | 2021-1-27 06:09:31 | 显示全部楼层 |阅读模式
本人今日脑瓜一热,忽然想在游戏中制作一个能检测当前电脑CPU占用率的功能。
我知道这听起来很蠢,所以请不要在这一点上浪费时间了。
首先我引用了几个必要的库:
usingUnityEngine;
usingSystem.Collections;
usingSystem.Text;
usingSystem;
usingSystem.Runtime.InteropServices;
usingSystem.Diagnostics;
usingSystem.Threading;
然后运行环境设置为.net2.0,然后用如下代码申请了一个全局的CPU监视器类
PerformanceCounterpc=newPerformanceCounter("Processor","%ProcessorTime","_Total");
调用PerformanceCounter类中的nextvalue函数获得cpu占用率值并输出到unity控制台:
privatevoidPerformanceCounterFun()
{
cpuLoad=pc.NextValue();
UnityEngine.Debug.Log("CPUload="+cpuLoad+"%.");
UnityEngine.Debug.Log(pc.NextValue());
}
然后设置其每隔1.5秒执行一次:
IEnumeratorstartCount(){
while(true)
{
yieldreturnnewWaitForSeconds(1.5f);
PerformanceCounterFun();
}
}
然而实际运行起来后发现,除了第一次计数是0以外,后面的cpu占用率计数值始终为100,而资源管理器中的显示数值仅有不到20%。。。我尝试建立一个C#控制台应用程序来做同样的功能,能够输出较准确的值,因此API本身应该是没错的。我现在十分好奇为何在UNITY中我会一直得到100这个值。。。。。
本人小白,求大神讲解。。。。。

分 -->
回复

使用道具 举报

千问 | 2021-1-27 06:09:31 | 显示全部楼层
←_←表示占用率这个东东运行较慢
好吧干货给你
privatePerformanceCounterpcCpuLoad=newPerformanceCounter("Processor","%ProcessorTime","_Total");
#regionAPI
//获取CPU占用率
publicfloatCpuLoad{
get{
returnpcCpuLoad.NextValue();
}
}
#endregion
执行输出
Console.WriteLine("CCCCCCC"+CpuLoad);
回复

使用道具 举报

千问 | 2021-1-27 06:09:31 | 显示全部楼层
引用1楼qq_26597393的回复:←_←表示占用率这个东东运行较慢
好吧干货给你
privatePerformanceCounterpcCpuLoad=newPerformanceCounter("Processor","%ProcessorTime","_Total");
#regionAPI
//获取CPU占用率
publicfloatCpuLoad{
get{
returnpcCpuLoad.NextValue();
}
}
#endregion
执行输出
Console.WriteLine("CCCCCCC"+CpuLoad);

引用1楼qq_26597393的回复:←_←表示占用率这个东东运行较慢
好吧干货给你
privatePerformanceCounterpcCpuLoad=newPerformanceCounter("Processor","%ProcessorTime","_Total");
#regionAPI
//获取CPU占用率
publicfloatCpuLoad{
get{
returnpcCpuLoad.NextValue();
}
}
#endregion
执行输出
Console.WriteLine("CCCCCCC"+CpuLoad);
我忘了这个usingSystem.Diagnostics;
回复

使用道具 举报

千问 | 2021-1-27 06:09:31 | 显示全部楼层
没啥用啊老哥。。返回值依然一直是100啊。。
回复

使用道具 举报

千问 | 2021-1-27 06:09:31 | 显示全部楼层
还是100?我自己试了可以使用啊。。。
回复

使用道具 举报

千问 | 2021-1-27 06:09:31 | 显示全部楼层
你确定你是在unity下用的吗。。。。能不能给发我一个能用的的工程。。。。
回复

使用道具 举报

千问 | 2021-1-27 06:09:31 | 显示全部楼层
使用get语句的意义是什么?。。
回复

使用道具 举报

千问 | 2021-1-27 06:09:31 | 显示全部楼层
没有任何意义。。。习惯使用get了。。。
回复

使用道具 举报

千问 | 2021-1-27 06:09:31 | 显示全部楼层
好的我给你写一个吧
回复

使用道具 举报

千问 | 2021-1-27 06:09:31 | 显示全部楼层
我擦嘞我这个API是写在服务器中的并不是挂在unity中的
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行