如何读取系统使用情况(CPU,RAM等)

时间:2019-06-20 10:44:41

标签: c# unity3d .net-4.0

在unity3d中,我试图读取系统使用情况,以便在有人玩VR游戏时查看CPU和RAM的使用情况。我知道如何在计算机屏幕上显示它,以及如何使其远离播放器VR屏幕。

据我所知,我一直在Google各处搜寻。它们中的大多数会导致相同的答案,而我似乎无法正常工作。

我一直在查看帖子:https://answers.unity.com/questions/506736/measure-cpu-and-memory-load-in-code.html,这使我进入了stackoverflow页面:How to get the CPU Usage in C#?

在这些文章中,即使这是不正确的,他们也总是遇到CPU使用率保持在100%的问题。我一直在尝试System.Threading.Thread.Sleep(1000)。但这会将整个游戏锁定为1fps,因为它每秒等待1秒。而且即使是1fps,我也只能读取100%的内容。

在这段代码中,我使用的是Sleep线程,它将游戏速度降低到1fps

using UnityEngine;
using System.Diagnostics;
using TMPro;

public class DebugUIManager : MonoBehaviour
{
    private PerformanceCounter cpuCounter;
    [SerializeField] private TMP_Text cpuCounterText;

    private void Start()
    {
        cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
    }

    private void Update()
    {
        cpuCounterText.text = getCurrentCpuUsage();
    }

    private string getCurrentCpuUsage()
    {
        dynamic firstValue = cpuCounter.NextValue() + "% CPU";
        System.Threading.Thread.Sleep(1000);
        dynamic secondValue = cpuCounter.NextValue() + "% CPU";

        return secondValue;
    }
}

每当我更改

    private string getCurrentCpuUsage()
    {
        dynamic firstValue = cpuCounter.NextValue() + "% CPU";
        System.Threading.Thread.Sleep(1000);
        dynamic secondValue = cpuCounter.NextValue() + "% CPU";

        return secondValue;
    }

    private string getCurrentCpuUsage()
    {
        return cpuCounter.NextValue() + "%";
    }

该游戏的fps不会下降,但它仍然无法执行任何操作。

我没有收到任何错误消息,因为它运行没有问题。但是我真的很想知道如何获得CPU使用率,因此我自己可以解决其余的问题。

任何有助于解决问题的答案。

1 个答案:

答案 0 :(得分:1)

我尝试了此操作,也无法让PerformanceCounter正常运行(总是像您一样返回100%

但是我找到了一个不错的选择here,并用它来重新构建您的DebugUIManager

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 performance
            Priority = 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 manually
        processorCount = 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 changed
        if (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 range
        if (CpuUsage < 0 || CpuUsage > 100) return;

        // I used a float instead of int for the % so use the ToString you like for displaying it
        cpuCounterText.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 thread
        while (true)
        {
            var cpuTime = new TimeSpan(0);

            // Get a list of all running processes in this PC
            var AllProcesses = Process.GetProcesses();

            // Sum up the total processor time of all running processes
            cpuTime = AllProcesses.Aggregate(cpuTime, (current, process) => current + process.TotalProcessorTime);

            // get the difference between the total sum of processor times
            // and the last time we called this
            var newCPUTime = cpuTime - lastCpuTime;

            // update the value of _lastCpuTime
            lastCpuTime = 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 count
            CpuUsage = 100f * (float)newCPUTime.TotalSeconds / updateInterval / processorCount;

            // Wait for UpdateInterval
            Thread.Sleep(Mathf.RoundToInt(updateInterval * 1000));
        }
    }
}

enter image description here

相关问题