-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMemoryUsageLogger.cs
More file actions
336 lines (292 loc) · 11.1 KB
/
Copy pathMemoryUsageLogger.cs
File metadata and controls
336 lines (292 loc) · 11.1 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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
// *********************************************************************************************************
// Written by Matthew Monroe for the US Department of Energy
// Pacific Northwest National Laboratory, Richland, WA
// Created 02/09/2009
// Last updated 02/03/2016
// *********************************************************************************************************
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
namespace ValidateFastaFile
{
/// <summary>
/// Memory usage logger
/// </summary>
public class MemoryUsageLogger
{
// Ignore Spelling: yyyy-MM-dd, hh:mm:ss tt, nonpaged
// The minimum interval between appending a new memory usage entry to the log
private float mMinimumMemoryUsageLogIntervalMinutes = 1;
// Used to determine the amount of free memory
private PerformanceCounter mPerfCounterFreeMemory;
private PerformanceCounter mPerfCounterPoolPagedBytes;
private PerformanceCounter mPerfCounterPoolNonpagedBytes;
private bool mPerfCountersInitialized;
private readonly List<string> mHeaderNames;
private readonly List<int> mHeaderNameLengths;
/// <summary>
/// Output folder for the log file
/// </summary>
/// <remarks>If this is an empty string, the log file is created in the working directory</remarks>
public string LogFolderPath { get; }
/// <summary>
/// The minimum interval between appending a new memory usage entry to the log
/// </summary>
public float MinimumLogIntervalMinutes
{
get => mMinimumMemoryUsageLogIntervalMinutes;
set
{
if (value < 0)
value = 0;
mMinimumMemoryUsageLogIntervalMinutes = value;
}
}
/// <summary>
/// Constructor
/// </summary>
/// <remarks>
/// Use WriteMemoryUsageLogEntry to append an entry to the log file.
/// Alternatively use GetMemoryUsageSummary() to retrieve the memory usage as a string</remarks>
/// <param name="logFolderPath">Folder in which to write the memory log file(s); if this is an empty string, the log file is created in the working directory</param>
/// <param name="minLogIntervalMinutes">Minimum log interval, in minutes</param>
public MemoryUsageLogger(string logFolderPath, float minLogIntervalMinutes = 5)
{
if (string.IsNullOrWhiteSpace(logFolderPath))
{
LogFolderPath = string.Empty;
}
else
{
LogFolderPath = logFolderPath;
}
MinimumLogIntervalMinutes = minLogIntervalMinutes;
mHeaderNames = new List<string>
{
"Date".PadRight(10),
"Time".PadRight(11),
"ProcessMemoryUsage_MB",
"FreeMemory_MB",
"PoolPaged_MB",
"PoolNonpaged_MB"
};
mHeaderNameLengths = new List<int>();
foreach (var item in mHeaderNames)
{
mHeaderNameLengths.Add(item.Length + 2);
}
}
/// <summary>
/// Returns the amount of free memory on the current machine
/// </summary>
/// <returns>Free memory, in MB</returns>
public float GetFreeMemoryMB()
{
try
{
if (mPerfCounterFreeMemory == null)
{
return 0;
}
return mPerfCounterFreeMemory.NextValue();
}
catch (Exception)
{
// Ignore errors here
return -1;
}
}
/// <summary>
/// Return the memory usage columns as a space or tab-separated list
/// </summary>
/// <param name="tabSeparated"></param>
public string GetMemoryUsageHeader(bool tabSeparated = false)
{
return GetFormattedValues(mHeaderNames, mHeaderNameLengths, tabSeparated);
}
/// <summary>
/// Get memory usage data as a space or tab-separated list
/// </summary>
/// <param name="tabSeparated"></param>
public string GetMemoryUsageSummary(bool tabSeparated = false)
{
if (!mPerfCountersInitialized)
{
InitializePerfCounters();
}
var currentTime = DateTime.Now;
var dataValues = new List<string>
{
currentTime.ToString("yyyy-MM-dd"),
currentTime.ToString("hh:mm:ss tt"),
GetProcessMemoryUsageMB().ToString("0.0"),
GetFreeMemoryMB().ToString("0.0"),
GetPoolPagedMemory().ToString("0.0"),
GetPoolNonpagedMemory().ToString("0.0")
};
return GetFormattedValues(dataValues, mHeaderNameLengths, tabSeparated);
}
/// <summary>
/// Returns the amount of pool nonpaged memory on the current machine
/// </summary>
/// <returns>Pool Nonpaged memory, in MB</returns>
public float GetPoolNonpagedMemory()
{
try
{
if (mPerfCounterPoolNonpagedBytes == null)
{
return 0;
}
else
{
return (float)(mPerfCounterPoolNonpagedBytes.NextValue() / 1024.0 / 1024);
}
}
catch (Exception)
{
// Ignore errors here
return -1;
}
}
/// <summary>
/// Returns the amount of pool paged memory on the current machine
/// </summary>
/// <returns>Pool Paged memory, in MB</returns>
public float GetPoolPagedMemory()
{
try
{
if (mPerfCounterPoolPagedBytes == null)
{
return 0;
}
return (float)(mPerfCounterPoolPagedBytes.NextValue() / 1024.0 / 1024);
}
catch (Exception)
{
// Ignore errors here
return -1;
}
}
/// <summary>
/// Returns the amount of memory that the currently running process is using
/// </summary>
/// <returns>Memory usage, in MB</returns>
public static float GetProcessMemoryUsageMB()
{
try
{
// Obtain a handle to the current process
var objProcess = Process.GetCurrentProcess();
// The WorkingSet is the total physical memory usage
return (float)(objProcess.WorkingSet64 / 1024.0 / 1024);
}
catch (Exception)
{
// Ignore errors here
return 0;
}
}
/// <summary>
/// Initializes the performance counters
/// </summary>
/// <returns>Any errors that occur; empty string if no errors</returns>
public string InitializePerfCounters()
{
var msgErrors = string.Empty;
try
{
mPerfCounterFreeMemory = new PerformanceCounter("Memory", "Available MBytes") { ReadOnly = true };
}
catch (Exception ex)
{
if (msgErrors.Length > 0)
msgErrors += "; ";
msgErrors += "Error instantiating the Memory: 'Available MBytes' performance counter: " + ex.Message;
}
try
{
mPerfCounterPoolPagedBytes = new PerformanceCounter("Memory", "Pool Paged Bytes") { ReadOnly = true };
}
catch (Exception ex)
{
if (msgErrors.Length > 0)
msgErrors += "; ";
msgErrors += "Error instantiating the Memory: 'Pool Paged Bytes' performance counter: " + ex.Message;
}
try
{
mPerfCounterPoolNonpagedBytes =
new PerformanceCounter("Memory", "Pool NonPaged Bytes") { ReadOnly = true };
}
catch (Exception ex)
{
if (msgErrors.Length > 0)
msgErrors += "; ";
msgErrors += "Error instantiating the Memory: 'Pool NonPaged Bytes' performance counter: " + ex.Message;
}
mPerfCountersInitialized = true;
return msgErrors;
}
private DateTime dtLastWriteTime = DateTime.UtcNow.Subtract(TimeSpan.FromHours(1));
private string GetFormattedValues(
IReadOnlyList<string> values,
IReadOnlyList<int> headerNameLengths,
bool tabSeparated = false)
{
if (tabSeparated)
{
var trimmedValues = values.Select(item => item.Trim()).ToList();
return string.Join("\t", trimmedValues);
}
var dataLine = new StringBuilder();
for (var i = 0; i < headerNameLengths.Count; i++)
{
dataLine.Append(values[i].PadRight(headerNameLengths[i]));
}
return dataLine.ToString();
}
/// <summary>
/// Writes a status file tracking memory usage
/// </summary>
// ReSharper disable once UnusedMember.Global
public void WriteMemoryUsageLogEntry()
{
try
{
if (DateTime.UtcNow.Subtract(dtLastWriteTime).TotalMinutes < mMinimumMemoryUsageLogIntervalMinutes)
{
// Not enough time has elapsed since the last write; exit sub
return;
}
dtLastWriteTime = DateTime.UtcNow;
// We're creating a new log file each month
var logFileName = "MemoryUsageLog_" + DateTime.Now.ToString("yyyy-MM") + ".txt";
string logFilePath;
if (!string.IsNullOrWhiteSpace(LogFolderPath))
{
logFilePath = Path.Combine(LogFolderPath, logFileName);
}
else
{
logFilePath = logFileName;
}
var writeHeader = !File.Exists(logFilePath);
using var writer = new StreamWriter(new FileStream(logFilePath, FileMode.Append, FileAccess.Write, FileShare.Read));
if (writeHeader)
{
GetMemoryUsageHeader(true);
}
writer.WriteLine(GetMemoryUsageSummary(true));
}
catch
{
// Ignore errors here
}
}
}
}