-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCPUMon.cs
87 lines (72 loc) · 2.47 KB
/
CPUMon.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using Godot;
using System;
using System.Diagnostics.Tracing;
using System.Collections.Generic;
using System.Linq;
public sealed class SystemRuntimeEventListener : EventListener
{
public double Value { get; private set; }
protected override void OnEventSourceCreated(EventSource eventSource)
{
if (eventSource.Name.Equals("System.Runtime"))
EnableEvents(eventSource, EventLevel.LogAlways, EventKeywords.All, new Dictionary<string, string> { {"EventCounterIntervalSec", "1"} });
}
protected override void OnEventWritten(EventWrittenEventArgs eventData)
{
if (eventData.Payload == null || eventData.Payload.Count == 0)
return;
if (eventData.Payload[0] is IDictionary<string, object> eventPayload &&
eventPayload.TryGetValue("Name", out var nameData) && nameData is string name && name == "cpu-usage")
{
if (eventPayload.TryGetValue("Mean", out var value))
{
if (value is double dValue)
{
Value = dValue;
base.OnEventWritten(eventData);
}
}
}
}
}
public class CPUMon : Label
{
// cpuCounter = new EventCounter("Processor", "% Processor Time", "_Total");
// ramCounter = new EventCounter("Memory", "Available MBytes");
SystemRuntimeEventListener listener;
SceneTreeTimer timer; float updateTimeout = 0.5f;
public override void _Ready()
{
if(!Visible) return;
listener = new SystemRuntimeEventListener();
timer = GetTree().CreateTimer(updateTimeout);
timer.Connect("timeout", this, "UpdateCounters");
}
// Called every frame. 'delta' is the elapsed time since the previous frame.
ulong lastTick;
List<ulong> ticks = new List<ulong>(512);
public override void _Process(float delta)
{
var t = OS.GetTicksUsec();
ticks.Add(t-lastTick);
lastTick = t;
// Text = "CPU: " + listener.Value.ToString() + "%" ;
}
public void UpdateCounters()
{
timer = GetTree().CreateTimer(updateTimeout);
timer.Connect("timeout", this, "UpdateCounters");
Text = "Avg Tick time: " + Avg(ticks).ToString() + " uSec\n";
Text += "Static Mem: " + (OS.GetStaticMemoryUsage()/(float)0x10_0000).ToString() + " Mb" ;
ticks.Clear();
}
float Avg<T>(List<T> arr) where T : struct
{
long sum = 0;
for (int i=0; i < arr.Count; i++)
{
sum += (long) Convert.ToInt64(arr[i]);
}
return sum / (float)arr.Count;
}
}