- Home /
How to use PerformanceCounter(C#) in Unity
I want to use some method of System.Diagnostics.PerformanceCounter such as getting CPU's or Memory's using rate. So I write the code(C#):
public class Test : MonoBehaviour
{
//counter category
private const string catCpu = "Processor";
private const string catMem = "Memory";
private const string catPhy = "PhysicalDisk";
//counter name
private const string countCpu = "% Processor Time";
private const string countMem = "Available MBytes";
private const string countPhy = "% Disk Time";
//instance name
private const string instanceCpu = "_Total";
private const string instancePhy = "_Total";
//value name
private float vaCpu;
private float vaMem;
private float vaPhy;
void Update() {
PerformanceCounter pcCpu;
PerformanceCounter pcMem;
PerformanceCounter pcPhy;
// CPU
try {
pcCpu = new PerformanceCounter(catCpu, countCpu, instanceCpu);
vaCpu = pcCpu.NextValue() * 100.0f;
UnityEngine.Debug.Log(vaCpu+" %");
} catch(InvalidOperationException) {
vaCpu = 50.0f;
UnityEngine.Debug.Log("Cannot get infomation about this PC's CPU");
}
// Memory
...
// Physical Disk
...
}
But I receive this result as : 0% 0MB 0%
I wondered this result, so I created similar C# code, compiled that , and ran.
That result was as same as value of Performance Monitor(Windows application), so it was running undoubtedly.
Please tell me this solution.
@elect000
use syntacx
public class Test : $$anonymous$$onoBehaviour
{
//counter category
private const string catCpu = "Processor";
private const string cat$$anonymous$$em = "$$anonymous$$emory";
private const string catPhy = "PhysicalDisk";
//counter name
private const string countCpu = "% Processor Time";
private const string count$$anonymous$$em = "Available $$anonymous$$Bytes";
private const string countPhy = "% Disk Time";
//instance name
private const string instanceCpu = "_Total";
private const string instancePhy = "_Total";
//value name
private float vaCpu;
private float va$$anonymous$$em;
private float vaPhy;
void Update() {
PerformanceCounter pcCpu;
PerformanceCounter pc$$anonymous$$em;
PerformanceCounter pcPhy;
// CPU
try {
pcCpu = new PerformanceCounter(catCpu, countCpu, instanceCpu);
vaCpu = pcCpu.NextValue() * 100.0f;
UnityEngine.Debug.Log(vaCpu+" %");
} catch(InvalidOperationException) {
vaCpu = 50.0f;
UnityEngine.Debug.Log("Cannot get infomation about this PC's CPU");
}
// $$anonymous$$emory
...
// Physical Disk
...
}
Your answer

Follow this Question
Related Questions
PerformanceCounters return 0MB RAM and %100 CPU in Unity 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Question about C# parameters 2 Answers
Wave Spawner not working |Does not detect if an object is destroyed 1 Answer