Unity获取CPU占有率

2023-11-20 16:59
文章标签 cpu 获取 unity 占有率

本文主要是介绍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占有率的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/396081

相关文章

Linux下进程的CPU配置与线程绑定过程

《Linux下进程的CPU配置与线程绑定过程》本文介绍Linux系统中基于进程和线程的CPU配置方法,通过taskset命令和pthread库调整亲和力,将进程/线程绑定到特定CPU核心以优化资源分配... 目录1 基于进程的CPU配置1.1 对CPU亲和力的配置1.2 绑定进程到指定CPU核上运行2 基于

Python使用OpenCV实现获取视频时长的小工具

《Python使用OpenCV实现获取视频时长的小工具》在处理视频数据时,获取视频的时长是一项常见且基础的需求,本文将详细介绍如何使用Python和OpenCV获取视频时长,并对每一行代码进行深入解析... 目录一、代码实现二、代码解析1. 导入 OpenCV 库2. 定义获取视频时长的函数3. 打开视频文

MySQL 获取字符串长度及注意事项

《MySQL获取字符串长度及注意事项》本文通过实例代码给大家介绍MySQL获取字符串长度及注意事项,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录mysql 获取字符串长度详解 核心长度函数对比⚠️ 六大关键注意事项1. 字符编码决定字节长度2

python3如何找到字典的下标index、获取list中指定元素的位置索引

《python3如何找到字典的下标index、获取list中指定元素的位置索引》:本文主要介绍python3如何找到字典的下标index、获取list中指定元素的位置索引问题,具有很好的参考价值,... 目录enumerate()找到字典的下标 index获取list中指定元素的位置索引总结enumerat

SpringMVC高效获取JavaBean对象指南

《SpringMVC高效获取JavaBean对象指南》SpringMVC通过数据绑定自动将请求参数映射到JavaBean,支持表单、URL及JSON数据,需用@ModelAttribute、@Requ... 目录Spring MVC 获取 JavaBean 对象指南核心机制:数据绑定实现步骤1. 定义 Ja

C++中RAII资源获取即初始化

《C++中RAII资源获取即初始化》RAII通过构造/析构自动管理资源生命周期,确保安全释放,本文就来介绍一下C++中的RAII技术及其应用,具有一定的参考价值,感兴趣的可以了解一下... 目录一、核心原理与机制二、标准库中的RAII实现三、自定义RAII类设计原则四、常见应用场景1. 内存管理2. 文件操

SpringBoot服务获取Pod当前IP的两种方案

《SpringBoot服务获取Pod当前IP的两种方案》在Kubernetes集群中,SpringBoot服务获取Pod当前IP的方案主要有两种,通过环境变量注入或通过Java代码动态获取网络接口IP... 目录方案一:通过 Kubernetes Downward API 注入环境变量原理步骤方案二:通过

使用Python实现获取屏幕像素颜色值

《使用Python实现获取屏幕像素颜色值》这篇文章主要为大家详细介绍了如何使用Python实现获取屏幕像素颜色值,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 一、一个小工具,按住F10键,颜色值会跟着显示。完整代码import tkinter as tkimport pyau

Java进程CPU使用率过高排查步骤详细讲解

《Java进程CPU使用率过高排查步骤详细讲解》:本文主要介绍Java进程CPU使用率过高排查的相关资料,针对Java进程CPU使用率高的问题,我们可以遵循以下步骤进行排查和优化,文中通过代码介绍... 目录前言一、初步定位问题1.1 确认进程状态1.2 确定Java进程ID1.3 快速生成线程堆栈二、分析

python获取cmd环境变量值的实现代码

《python获取cmd环境变量值的实现代码》:本文主要介绍在Python中获取命令行(cmd)环境变量的值,可以使用标准库中的os模块,需要的朋友可以参考下... 前言全局说明在执行py过程中,总要使用到系统环境变量一、说明1.1 环境:Windows 11 家庭版 24H2 26100.4061