Rick Rasenberg
Rick Rasenberg

Reputation: 25

How to read system usage (CPU, RAM etc)

In unity3d I'm trying to read the system usage in order to see the CPU and RAM usage whilst a person is playing a VR game. I know how I can show it on the computer screen and how to keep it away from the players VR screen.

I have been looking all around Google for as far as I know. Most of them lead to the same answer which I cannot seem to get working correctly.

I have been checking out the post: https://answers.unity.com/questions/506736/measure-cpu-and-memory-load-in-code.html which leads me to the stackoverflow page: How to get the CPU Usage in C#?

In these posts they always get the problem of having the CPU usage stuck at 100%, even though this is incorrect. I have been trying the System.Threading.Thread.Sleep(1000). But this locks the entire game to 1fps due to it waiting 1 sec every second. And even with having 1fps I cannot get any other read than 100%.

In this code I'm using the Sleep thread which slows down the game to 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;
    }
}

Whenever I change the

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

        return secondValue;
    }

to

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

the game won't get dropped in fps, but it also doesn't do anything still.

I haven't been getting any error messages because it runs without issues. But I would really like to know how to get the CPU usage, so I can figure out the rest myself.

Any answers helping would be appreciated.

Upvotes: 0

Views: 5925

Answers (1)

derHugo
derHugo

Reputation: 90590

I tried this and also couldn't get PerformanceCounter to run correctly (always returned 100% like for you)

However I've found a good alternative here and used it to re-build your DebugUIManager on it

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

Upvotes: 3

Related Questions