This repository was archived by the owner on Jan 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathPerformanceMonitor.cs
More file actions
187 lines (161 loc) · 6.15 KB
/
PerformanceMonitor.cs
File metadata and controls
187 lines (161 loc) · 6.15 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#nullable enable
using System;
using System.Diagnostics;
using System.Threading;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Microsoft.Quantum.IQSharp
{
public record class DeviceCapabilitiesEvent : Event<DeviceCapabilitiesArgs>;
#if NET5_0 || NET6_0 || NET5_0_OR_GREATER
public record DeviceCapabilitiesArgs
#else
public class DeviceCapabilitiesArgs
#endif
{
public uint? NProcessors { get; set; } = null;
public uint? TotalMemoryInGiB { get; set; } = null;
}
public class PerformanceMonitor : IPerformanceMonitor
{
protected class TaskReporter : ITaskReporter
{
private readonly PerformanceMonitor monitor;
private readonly Stopwatch stopwatch = new Stopwatch();
private readonly TimeSpan startedAt;
internal TaskReporter(PerformanceMonitor monitor, ITaskReporter? parent, string description, string id)
{
this.monitor = monitor;
this.Parent = parent;
this.Description = description;
this.Id = id;
startedAt = parent?.TimeSinceStart ?? TimeSpan.Zero;
stopwatch.Start();
}
public string Description { get; }
public string Id { get; }
public ITaskReporter? Parent { get; }
public TimeSpan TimeSinceStart => stopwatch.Elapsed;
public TimeSpan TotalTimeSinceStart => TimeSinceStart + startedAt;
public ITaskReporter BeginSubtask(string description, string id) =>
new TaskReporter(monitor, this, description, id);
public void Dispose()
{
stopwatch.Stop();
monitor.OnTaskCompleteAvailable?.Invoke(this.monitor, new TaskCompleteArgs(
this, ((ITaskReporter)this).TotalTimeSinceStart
));
}
public void ReportStatus(string description, string id) =>
monitor.OnTaskPerformanceAvailable?.Invoke(this.monitor, new TaskPerformanceArgs(
this,
description,
id,
((ITaskReporter)this).TotalTimeSinceStart
));
}
private bool alive = false;
private Thread? thread = null;
public bool EnableBackgroundReporting
{
get => alive;
set
{
if (alive == value)
{
// No changes needed, return.
return;
}
if (alive && !value)
{
// Running, but need to stop.
Stop();
}
else
{
// Stopped, but need to run.
Start();
}
}
}
public PerformanceMonitor(IEventService? eventService = null, ILogger<PerformanceMonitor>? logger = null)
{
eventService?.TriggerServiceInitialized<IPerformanceMonitor>(this);
// Get client capabilities in the background so as to not block the
// constructor.
new Thread(async () =>
{
var args = new DeviceCapabilitiesArgs
{
NProcessors = (uint)System.Environment.ProcessorCount,
// Round to nearest GiB so as to avoid collecting too much
// entropy.
TotalMemoryInGiB = await PlatformUtils.GetTotalMemory(logger) is ulong nBytes
? (uint?)(nBytes / 1024 / 1024 / 1024)
: (uint?)null
};
logger?.LogInformation("Reporting device capabilities: {Capabilities}", args);
eventService?.Trigger<DeviceCapabilitiesEvent, DeviceCapabilitiesArgs>(args);
}).Start();
OnTaskPerformanceAvailable += (sender, args) =>
{
logger?.LogDebug("[{TimeSinceStart}] {Task} / {Description}", args.TimeSinceTaskStart, args.Task.Description, args.StatusDescription);
};
}
/// <inheritdoc />
public event EventHandler<SimulatorPerformanceArgs>? OnSimulatorPerformanceAvailable;
/// <inheritdoc />
public event EventHandler<KernelPerformanceArgs>? OnKernelPerformanceAvailable;
public event EventHandler<TaskPerformanceArgs>? OnTaskPerformanceAvailable;
public event EventHandler<TaskCompleteArgs>? OnTaskCompleteAvailable;
/// <inheritdoc />
public void Report()
{
var managedRamUsed = GC.GetTotalMemory(forceFullCollection: false);
var totalRamUsed = Process.GetCurrentProcess().WorkingSet64;
OnKernelPerformanceAvailable?.Invoke(this, new KernelPerformanceArgs(
managedRamUsed, totalRamUsed
));
}
/// <inheritdoc />
public void Start()
{
if (!alive)
{
alive = true;
thread = new Thread(EventLoop);
thread.Start();
}
}
/// <inheritdoc />
protected void Join() => thread?.Join();
/// <inheritdoc />
protected void Stop()
{
alive = false;
thread?.Interrupt();
Join();
thread = null;
}
protected void EventLoop()
{
while (alive)
{
Report();
Thread.Sleep(15000);
}
}
/// <summary>
/// Given a new simulator performance record, emits an event with
/// that performance data.
/// </summary>
public void ReportSimulatorPerformance(SimulatorPerformanceArgs args)
{
this.OnSimulatorPerformanceAvailable?.Invoke(this, args);
}
public ITaskReporter BeginTask(string description, string id) =>
new TaskReporter(this, null, description, id);
}
}