-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
1038 lines (908 loc) · 45 KB
/
Copy pathProgram.cs
File metadata and controls
1038 lines (908 loc) · 45 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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace NetPulse
{
internal static class Program
{
private static volatile bool _stopRequested;
private static int _markerRequests;
private static int Main(string[] args)
{
return Run(args, false, null, null);
}
public static int RunEmbedded(string targetProcessName, Action<Sample> sampleCallback, Action<SessionResult> completionCallback)
{
return RunEmbedded(targetProcessName, sampleCallback, completionCallback, false);
}
public static int RunEmbedded(string targetProcessName, Action<Sample> sampleCallback, Action<SessionResult> completionCallback, bool markFirstSample)
{
if (string.IsNullOrWhiteSpace(targetProcessName))
return Run(new[] { "--quiet", "--no-process" }, true, sampleCallback, completionCallback, markFirstSample ? 1 : 0);
return Run(new[] { "--quiet", "--process", targetProcessName.Trim() }, true, sampleCallback, completionCallback, markFirstSample ? 1 : 0);
}
public static void RequestStop()
{
_stopRequested = true;
}
public static void RequestMarker()
{
Interlocked.Increment(ref _markerRequests);
}
private static int Run(string[] args, bool embeddedMode, Action<Sample> sampleCallback, Action<SessionResult> completionCallback, int initialMarkerRequests = 0)
{
_stopRequested = false;
Interlocked.Exchange(ref _markerRequests, Math.Max(0, initialMarkerRequests));
if (!embeddedMode)
Console.OutputEncoding = new UTF8Encoding(false);
if (args.Any(a => string.Equals(a, "--help", StringComparison.OrdinalIgnoreCase) || a == "-h"))
{
PrintHelp();
return 0;
}
string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
string configPath = Path.Combine(baseDirectory, "NetPulse.config.txt");
MonitorConfig config = MonitorConfig.Load(configPath);
string targetOverride = GetArgumentValue(args, "--target");
if (!string.IsNullOrWhiteSpace(targetOverride))
config.InternetTarget = targetOverride.Trim();
bool noTargetProcess = args.Any(a => string.Equals(a, "--no-process", StringComparison.OrdinalIgnoreCase));
string processOverride = GetArgumentValue(args, "--process");
string[] targetProcessNames = noTargetProcess
? new string[0]
: string.IsNullOrWhiteSpace(processOverride)
? new[] { "VALORANT-Win64-Shipping", "VALORANT" }
: processOverride.Split(new[] { '|', ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(name => name.Trim()).Where(name => name.Length > 0).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
if (!noTargetProcess && targetProcessNames.Length == 0)
targetProcessNames = new[] { "VALORANT-Win64-Shipping" };
string targetProcessDisplayName = string.Join("|", targetProcessNames);
int durationSeconds = ParseIntArgument(args, "--duration", 0);
bool quiet = args.Any(a => string.Equals(a, "--quiet", StringComparison.OrdinalIgnoreCase));
string logDirectory = Path.IsPathRooted(config.LogDirectory)
? config.LogDirectory
: Path.Combine(baseDirectory, config.LogDirectory);
Directory.CreateDirectory(logDirectory);
DateTime sessionStart = DateTime.Now;
string sessionId = sessionStart.ToString("yyyyMMdd_HHmmss", CultureInfo.InvariantCulture);
string sessionDirectory = Path.Combine(logDirectory, sessionId);
Directory.CreateDirectory(sessionDirectory);
string csvPath = Path.Combine(sessionDirectory, "session.csv");
string eventsPath = Path.Combine(sessionDirectory, "events.csv");
string summaryPath = Path.Combine(sessionDirectory, "summary.txt");
CpuSampler cpuSampler = new CpuSampler();
ProcessCpuSampler targetProcessSampler = new ProcessCpuSampler(targetProcessNames);
NetworkSampler networkSampler = new NetworkSampler(config);
SessionStatistics statistics = new SessionStatistics(config, targetProcessDisplayName);
EventTracker eventTracker = new EventTracker();
if (!embeddedMode)
{
Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs eventArgs)
{
eventArgs.Cancel = true;
_stopRequested = true;
};
}
try
{
using (StreamWriter csv = CreateUtf8Writer(csvPath))
using (StreamWriter events = CreateUtf8Writer(eventsPath))
{
csv.WriteLine("TimestampLocal,ElapsedSeconds,Mode,SystemCpuPct,MaxLogicalCpuPct,BusyLogicalCores,TargetProcess,TargetProcessRunning,TargetProcessCpuPct,Gateway,GatewayPingMs,GatewayStatus,InternetTarget,InternetPingMs,InternetStatus,InternetJitterMs,GatewayLoss60Pct,InternetLoss60Pct,DownloadKBps,UploadKBps,NetworkAdapter");
events.WriteLine("TimestampLocal,ElapsedSeconds,Event,State,Details,SystemCpuPct,MaxLogicalCpuPct,TargetProcess,TargetProcessRunning,TargetProcessCpuPct,GatewayPingMs,InternetPingMs,InternetJitterMs,DownloadKBps,UploadKBps");
if (!quiet)
{
Console.Title = "NetPulse - Network & CPU Monitor";
Console.WriteLine("NetPulse 已開始監測。按 M 標記異常,按 Q 或 Ctrl+C 停止。\n");
Console.WriteLine("網卡:{0}", networkSampler.AdapterDisplayName);
Console.WriteLine("閘道:{0} 外網目標:{1}", EmptyAsDash(networkSampler.GatewayAddress), config.InternetTarget);
Console.WriteLine("監測程式:{0}", targetProcessDisplayName);
Console.WriteLine("紀錄:{0}\n", csvPath);
}
cpuSampler.Prime();
targetProcessSampler.Prime();
networkSampler.PrimeTrafficCounters();
Stopwatch sessionClock = Stopwatch.StartNew();
double previousSampleAt = sessionClock.Elapsed.TotalSeconds;
long sampleNumber = 0;
while (!_stopRequested)
{
long targetElapsedMs = (sampleNumber + 1) * (long)config.SampleIntervalMs;
SleepUntil(sessionClock, targetElapsedMs);
if (_stopRequested)
break;
double nowSeconds = sessionClock.Elapsed.TotalSeconds;
double elapsedSincePrevious = Math.Max(0.001, nowSeconds - previousSampleAt);
previousSampleAt = nowSeconds;
CpuSnapshot cpu = cpuSampler.Sample();
ProcessCpuSnapshot targetProcess = targetProcessSampler.Sample(elapsedSincePrevious);
NetworkSnapshot network = networkSampler.Sample(elapsedSincePrevious);
string mode = targetProcess.IsRunning ? "TARGET" : "DAILY";
DateTime timestamp = DateTime.Now;
Sample sample = new Sample
{
Timestamp = timestamp,
ElapsedSeconds = nowSeconds,
Mode = mode,
TargetProcessName = targetProcessDisplayName,
Cpu = cpu,
Valorant = targetProcess,
Network = network
};
csv.WriteLine(BuildCsvRow(sample, config.InternetTarget, networkSampler.AdapterDisplayName));
eventTracker.Evaluate(sample, config, events);
int markerCount = Interlocked.Exchange(ref _markerRequests, 0);
for (int markerIndex = 0; markerIndex < markerCount; markerIndex++)
eventTracker.Mark(sample, "使用者手動標記:此刻感覺到卡頓、Ping異常或其他問題", events);
statistics.Add(sample);
if (sampleCallback != null)
{
try { sampleCallback(sample); }
catch { }
}
sampleNumber++;
if (sampleNumber % 10 == 0)
{
csv.Flush();
events.Flush();
}
if (!quiet)
{
DrawStatusLine(sample);
while (Console.KeyAvailable)
{
ConsoleKeyInfo key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Q)
_stopRequested = true;
else if (key.Key == ConsoleKey.M)
{
eventTracker.Mark(sample, "使用者手動標記:此刻感覺到卡頓、Ping異常或其他問題", events);
Console.Beep(900, 60);
}
}
}
if (durationSeconds > 0 && sessionClock.Elapsed.TotalSeconds >= durationSeconds)
_stopRequested = true;
}
csv.Flush();
events.Flush();
}
DateTime sessionEnd = DateTime.Now;
File.WriteAllText(summaryPath, statistics.BuildSummary(sessionStart, sessionEnd, csvPath, eventsPath), new UTF8Encoding(true));
if (completionCallback != null)
{
try
{
completionCallback(new SessionResult
{
Started = sessionStart,
Ended = sessionEnd,
CsvPath = csvPath,
EventsPath = eventsPath,
SummaryPath = summaryPath,
SessionDirectory = sessionDirectory,
TargetProcessName = targetProcessDisplayName
});
}
catch { }
}
if (!quiet)
{
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("監測已停止。");
Console.WriteLine("CSV:{0}", csvPath);
Console.WriteLine("事件:{0}", eventsPath);
Console.WriteLine("摘要:{0}", summaryPath);
}
return 0;
}
catch (Exception ex)
{
if (completionCallback != null)
{
try
{
completionCallback(new SessionResult
{
Started = sessionStart,
Ended = DateTime.Now,
CsvPath = csvPath,
EventsPath = eventsPath,
SummaryPath = summaryPath,
SessionDirectory = sessionDirectory,
ErrorMessage = ex.Message,
TargetProcessName = targetProcessDisplayName
});
}
catch { }
}
if (!embeddedMode)
{
Console.WriteLine();
Console.WriteLine("NetPulse 發生錯誤:{0}", ex.Message);
}
return 1;
}
}
private static StreamWriter CreateUtf8Writer(string path)
{
return new StreamWriter(new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read), new UTF8Encoding(true), 8192);
}
private static void SleepUntil(Stopwatch clock, long targetElapsedMs)
{
while (!_stopRequested)
{
long remaining = targetElapsedMs - clock.ElapsedMilliseconds;
if (remaining <= 0)
return;
Thread.Sleep((int)Math.Min(remaining, 100));
}
}
private static string BuildCsvRow(Sample sample, string internetTarget, string adapterName)
{
return string.Join(",", new[]
{
Csv(sample.Timestamp.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture)),
F(sample.ElapsedSeconds, "0.000"),
Csv(sample.Mode),
F(sample.Cpu.TotalCpuPercent, "0.0"),
F(sample.Cpu.MaxLogicalCpuPercent, "0.0"),
sample.Cpu.BusyLogicalCores.ToString(CultureInfo.InvariantCulture),
Csv(sample.TargetProcessName),
sample.Valorant.IsRunning ? "1" : "0",
F(sample.Valorant.CpuPercent, "0.0"),
Csv(sample.Network.GatewayAddress),
PingValue(sample.Network.GatewayPing),
Csv(sample.Network.GatewayPing.Status),
Csv(internetTarget),
PingValue(sample.Network.InternetPing),
Csv(sample.Network.InternetPing.Status),
F(sample.Network.InternetJitterMs, "0.0"),
F(sample.Network.GatewayLossPercent, "0.0"),
F(sample.Network.InternetLossPercent, "0.0"),
F(sample.Network.DownloadKBps, "0.0"),
F(sample.Network.UploadKBps, "0.0"),
Csv(adapterName)
});
}
private static void DrawStatusLine(Sample sample)
{
string gateway = sample.Network.GatewayPing.Success
? sample.Network.GatewayPing.RoundtripMs.ToString(CultureInfo.InvariantCulture) + "ms"
: "LOSS";
string internet = sample.Network.InternetPing.Success
? sample.Network.InternetPing.RoundtripMs.ToString(CultureInfo.InvariantCulture) + "ms"
: "LOSS";
string targetProcess = sample.Valorant.IsRunning
? string.Format(CultureInfo.InvariantCulture, "APP {0,5:0.0}%", sample.Valorant.CpuPercent)
: "APP -- ";
string line = string.Format(
CultureInfo.InvariantCulture,
"{0:HH:mm:ss} {1,-8} CPU {2,5:0.0}% CoreMax {3,5:0.0}% {4} | GW {5,5} NET {6,6} Jit {7,4:0.0} Loss {8,4:0.0}% | RX {9,7:0.0} TX {10,7:0.0} KB/s",
sample.Timestamp,
sample.Mode,
sample.Cpu.TotalCpuPercent,
sample.Cpu.MaxLogicalCpuPercent,
targetProcess,
gateway,
internet,
sample.Network.InternetJitterMs,
sample.Network.InternetLossPercent,
sample.Network.DownloadKBps,
sample.Network.UploadKBps);
int width = 160;
try { width = Math.Max(80, Console.WindowWidth - 1); }
catch { }
if (line.Length > width)
line = line.Substring(0, width);
else
line = line.PadRight(width);
Console.Write("\r" + line);
}
private static string PingValue(PingSample sample)
{
return sample.Success ? sample.RoundtripMs.ToString(CultureInfo.InvariantCulture) : string.Empty;
}
private static string F(double value, string format)
{
return value.ToString(format, CultureInfo.InvariantCulture);
}
private static string Csv(string value)
{
if (value == null)
return string.Empty;
if (value.IndexOfAny(new[] { ',', '"', '\r', '\n' }) < 0)
return value;
return "\"" + value.Replace("\"", "\"\"") + "\"";
}
private static string EmptyAsDash(string value)
{
return string.IsNullOrWhiteSpace(value) ? "--" : value;
}
private static string GetArgumentValue(string[] args, string name)
{
for (int i = 0; i < args.Length - 1; i++)
{
if (string.Equals(args[i], name, StringComparison.OrdinalIgnoreCase))
return args[i + 1];
}
return null;
}
private static int ParseIntArgument(string[] args, string name, int fallback)
{
string value = GetArgumentValue(args, name);
int parsed;
return int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out parsed) ? parsed : fallback;
}
private static void PrintHelp()
{
Console.WriteLine("NetPulse - Lightweight network and CPU monitor");
Console.WriteLine();
Console.WriteLine("用法:NetPulse.Console.exe [選項]");
Console.WriteLine(" --duration 秒數 指定監測時間;省略則持續到 Q/Ctrl+C");
Console.WriteLine(" --target 位址 暫時覆蓋外網 Ping 目標");
Console.WriteLine(" --process 名稱 要監測的程序名稱(不含 .exe)");
Console.WriteLine(" --no-process 不監測指定程序,只記錄 CPU 與網路");
Console.WriteLine(" --quiet 不更新主控台,只寫入紀錄");
Console.WriteLine(" --help 顯示此說明");
}
}
internal sealed class MonitorConfig
{
public int SampleIntervalMs = 1000;
public int PingTimeoutMs = 700;
public string InternetTarget = "1.1.1.1";
public double InternetSpikeMs = 80;
public double GatewaySpikeMs = 20;
public double TotalCpuSpikePercent = 90;
public double LogicalCpuSpikePercent = 95;
public int RollingWindowSamples = 60;
public string LogDirectory = "logs";
public static MonitorConfig Load(string path)
{
MonitorConfig config = new MonitorConfig();
if (!File.Exists(path))
return config;
foreach (string rawLine in File.ReadAllLines(path))
{
string line = rawLine.Trim();
if (line.Length == 0 || line.StartsWith("#", StringComparison.Ordinal))
continue;
int separator = line.IndexOf('=');
if (separator <= 0)
continue;
string key = line.Substring(0, separator).Trim();
string value = line.Substring(separator + 1).Trim();
int intValue;
double doubleValue;
if (key.Equals("SampleIntervalMs", StringComparison.OrdinalIgnoreCase) && int.TryParse(value, out intValue))
config.SampleIntervalMs = Math.Max(500, Math.Min(10000, intValue));
else if (key.Equals("PingTimeoutMs", StringComparison.OrdinalIgnoreCase) && int.TryParse(value, out intValue))
config.PingTimeoutMs = Math.Max(100, Math.Min(5000, intValue));
else if (key.Equals("InternetTarget", StringComparison.OrdinalIgnoreCase) && value.Length > 0)
config.InternetTarget = value;
else if (key.Equals("InternetSpikeMs", StringComparison.OrdinalIgnoreCase) && double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out doubleValue))
config.InternetSpikeMs = Math.Max(1, doubleValue);
else if (key.Equals("GatewaySpikeMs", StringComparison.OrdinalIgnoreCase) && double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out doubleValue))
config.GatewaySpikeMs = Math.Max(1, doubleValue);
else if (key.Equals("TotalCpuSpikePercent", StringComparison.OrdinalIgnoreCase) && double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out doubleValue))
config.TotalCpuSpikePercent = Math.Max(1, Math.Min(100, doubleValue));
else if (key.Equals("LogicalCpuSpikePercent", StringComparison.OrdinalIgnoreCase) && double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out doubleValue))
config.LogicalCpuSpikePercent = Math.Max(1, Math.Min(100, doubleValue));
else if (key.Equals("RollingWindowSamples", StringComparison.OrdinalIgnoreCase) && int.TryParse(value, out intValue))
config.RollingWindowSamples = Math.Max(10, Math.Min(3600, intValue));
else if (key.Equals("LogDirectory", StringComparison.OrdinalIgnoreCase) && value.Length > 0)
config.LogDirectory = value;
}
return config;
}
}
internal sealed class CpuSampler
{
private ProcessorTimes[] _previous;
public void Prime()
{
_previous = QueryProcessorTimes();
}
public CpuSnapshot Sample()
{
ProcessorTimes[] current = QueryProcessorTimes();
if (_previous == null || current == null || current.Length == 0 || _previous.Length != current.Length)
{
_previous = current;
return new CpuSnapshot();
}
double totalBusy = 0;
double totalTime = 0;
double maxCpu = 0;
int busyCores = 0;
for (int i = 0; i < current.Length; i++)
{
long idleDelta = current[i].IdleTime - _previous[i].IdleTime;
long kernelDelta = current[i].KernelTime - _previous[i].KernelTime;
long userDelta = current[i].UserTime - _previous[i].UserTime;
long timeDelta = kernelDelta + userDelta;
long busyDelta = timeDelta - idleDelta;
if (timeDelta <= 0)
continue;
double percent = Clamp(100.0 * busyDelta / timeDelta, 0, 100);
totalBusy += Math.Max(0, busyDelta);
totalTime += timeDelta;
maxCpu = Math.Max(maxCpu, percent);
if (percent >= 90)
busyCores++;
}
_previous = current;
return new CpuSnapshot
{
TotalCpuPercent = totalTime > 0 ? Clamp(100.0 * totalBusy / totalTime, 0, 100) : 0,
MaxLogicalCpuPercent = maxCpu,
BusyLogicalCores = busyCores
};
}
private static double Clamp(double value, double min, double max)
{
return Math.Max(min, Math.Min(max, value));
}
private static ProcessorTimes[] QueryProcessorTimes()
{
int processorCount = Environment.ProcessorCount;
int itemSize = Marshal.SizeOf(typeof(SystemProcessorPerformanceInformation));
int bufferSize = itemSize * processorCount;
IntPtr buffer = Marshal.AllocHGlobal(bufferSize);
try
{
int returnedLength;
int status = NtQuerySystemInformation(8, buffer, bufferSize, out returnedLength);
if (status != 0)
return null;
int actualCount = Math.Min(processorCount, returnedLength / itemSize);
ProcessorTimes[] values = new ProcessorTimes[actualCount];
for (int i = 0; i < actualCount; i++)
{
IntPtr itemPointer = IntPtr.Add(buffer, i * itemSize);
SystemProcessorPerformanceInformation item = (SystemProcessorPerformanceInformation)Marshal.PtrToStructure(itemPointer, typeof(SystemProcessorPerformanceInformation));
values[i] = new ProcessorTimes(item.IdleTime, item.KernelTime, item.UserTime);
}
return values;
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
[DllImport("ntdll.dll")]
private static extern int NtQuerySystemInformation(int systemInformationClass, IntPtr systemInformation, int systemInformationLength, out int returnLength);
[StructLayout(LayoutKind.Sequential)]
private struct SystemProcessorPerformanceInformation
{
public long IdleTime;
public long KernelTime;
public long UserTime;
public long DpcTime;
public long InterruptTime;
public uint InterruptCount;
}
private struct ProcessorTimes
{
public readonly long IdleTime;
public readonly long KernelTime;
public readonly long UserTime;
public ProcessorTimes(long idleTime, long kernelTime, long userTime)
{
IdleTime = idleTime;
KernelTime = kernelTime;
UserTime = userTime;
}
}
}
internal sealed class ProcessCpuSampler
{
private readonly string[] _processNames;
private Dictionary<int, TimeSpan> _previousCpuTimes = new Dictionary<int, TimeSpan>();
public ProcessCpuSampler(string[] processNames)
{
_processNames = processNames;
}
public void Prime()
{
_previousCpuTimes = ReadCpuTimes();
}
public ProcessCpuSnapshot Sample(double elapsedSeconds)
{
Dictionary<int, TimeSpan> current = ReadCpuTimes();
double usedMilliseconds = 0;
foreach (KeyValuePair<int, TimeSpan> pair in current)
{
TimeSpan previous;
if (_previousCpuTimes.TryGetValue(pair.Key, out previous))
usedMilliseconds += Math.Max(0, (pair.Value - previous).TotalMilliseconds);
}
_previousCpuTimes = current;
double denominator = elapsedSeconds * 1000.0 * Environment.ProcessorCount;
return new ProcessCpuSnapshot
{
IsRunning = current.Count > 0,
CpuPercent = denominator > 0 ? Math.Max(0, Math.Min(100, usedMilliseconds / denominator * 100.0)) : 0
};
}
private Dictionary<int, TimeSpan> ReadCpuTimes()
{
Dictionary<int, TimeSpan> result = new Dictionary<int, TimeSpan>();
HashSet<int> seen = new HashSet<int>();
foreach (string processName in _processNames)
{
Process[] processes;
try { processes = Process.GetProcessesByName(processName); }
catch { continue; }
foreach (Process process in processes)
{
try
{
if (seen.Add(process.Id))
result[process.Id] = process.TotalProcessorTime;
}
catch { }
finally { process.Dispose(); }
}
}
return result;
}
}
internal sealed class NetworkSampler
{
private readonly MonitorConfig _config;
private readonly Queue<bool> _gatewayWindow = new Queue<bool>();
private readonly Queue<bool> _internetWindow = new Queue<bool>();
private NetworkInterface _adapter;
private long _previousReceived;
private long _previousSent;
private long? _previousInternetRtt;
private double _jitter;
public string GatewayAddress { get; private set; }
public string AdapterDisplayName { get; private set; }
public NetworkSampler(MonitorConfig config)
{
_config = config;
ResolveActiveAdapter();
}
public void PrimeTrafficCounters()
{
long received;
long sent;
ReadTrafficCounters(out received, out sent);
_previousReceived = received;
_previousSent = sent;
}
public NetworkSnapshot Sample(double elapsedSeconds)
{
if (_adapter == null || _adapter.OperationalStatus != OperationalStatus.Up)
ResolveActiveAdapter();
PingSample gatewayPing = string.IsNullOrWhiteSpace(GatewayAddress)
? PingSample.Unavailable("NoGateway")
: PingHost(GatewayAddress, _config.PingTimeoutMs);
PingSample internetPing = PingHost(_config.InternetTarget, _config.PingTimeoutMs);
AddWindow(_gatewayWindow, gatewayPing.Success, _config.RollingWindowSamples);
AddWindow(_internetWindow, internetPing.Success, _config.RollingWindowSamples);
if (internetPing.Success)
{
if (_previousInternetRtt.HasValue)
{
double delta = Math.Abs(internetPing.RoundtripMs - _previousInternetRtt.Value);
_jitter += (delta - _jitter) / 16.0;
}
_previousInternetRtt = internetPing.RoundtripMs;
}
long received;
long sent;
ReadTrafficCounters(out received, out sent);
double download = elapsedSeconds > 0 ? Math.Max(0, received - _previousReceived) / elapsedSeconds / 1024.0 : 0;
double upload = elapsedSeconds > 0 ? Math.Max(0, sent - _previousSent) / elapsedSeconds / 1024.0 : 0;
_previousReceived = received;
_previousSent = sent;
return new NetworkSnapshot
{
GatewayAddress = GatewayAddress,
GatewayPing = gatewayPing,
InternetPing = internetPing,
InternetJitterMs = _jitter,
GatewayLossPercent = LossPercent(_gatewayWindow),
InternetLossPercent = LossPercent(_internetWindow),
DownloadKBps = download,
UploadKBps = upload
};
}
private void ResolveActiveAdapter()
{
_adapter = null;
GatewayAddress = string.Empty;
AdapterDisplayName = "未找到作用中的網路介面";
foreach (NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces())
{
if (adapter.OperationalStatus != OperationalStatus.Up || adapter.NetworkInterfaceType == NetworkInterfaceType.Loopback)
continue;
IPInterfaceProperties properties;
try { properties = adapter.GetIPProperties(); }
catch { continue; }
GatewayIPAddressInformation gateway = properties.GatewayAddresses.FirstOrDefault(g => g.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork && !g.Address.Equals(System.Net.IPAddress.Any));
if (gateway == null)
continue;
_adapter = adapter;
GatewayAddress = gateway.Address.ToString();
AdapterDisplayName = adapter.Name + " / " + adapter.Description;
return;
}
}
private void ReadTrafficCounters(out long received, out long sent)
{
received = 0;
sent = 0;
if (_adapter == null)
return;
try
{
IPv4InterfaceStatistics statistics = _adapter.GetIPv4Statistics();
received = statistics.BytesReceived;
sent = statistics.BytesSent;
}
catch { }
}
private static PingSample PingHost(string host, int timeoutMs)
{
try
{
using (Ping ping = new Ping())
{
PingReply reply = ping.Send(host, timeoutMs, new byte[8]);
if (reply != null && reply.Status == IPStatus.Success)
return new PingSample(true, reply.RoundtripTime, "Success");
return PingSample.Unavailable(reply == null ? "NoReply" : reply.Status.ToString());
}
}
catch (Exception ex)
{
return PingSample.Unavailable(ex.GetType().Name);
}
}
private static void AddWindow(Queue<bool> queue, bool value, int maximum)
{
queue.Enqueue(value);
while (queue.Count > maximum)
queue.Dequeue();
}
private static double LossPercent(Queue<bool> queue)
{
if (queue.Count == 0)
return 0;
return 100.0 * queue.Count(value => !value) / queue.Count;
}
}
internal sealed class EventTracker
{
private readonly Dictionary<string, bool> _states = new Dictionary<string, bool>();
public void Evaluate(Sample sample, MonitorConfig config, StreamWriter writer)
{
Set("TARGET_PROCESS_SESSION", sample.Valorant.IsRunning, sample, "目標程式狀態改變:" + sample.TargetProcessName, writer);
Set("TOTAL_CPU_HIGH", sample.Cpu.TotalCpuPercent >= config.TotalCpuSpikePercent, sample,
string.Format(CultureInfo.InvariantCulture, "總CPU {0:0.0}%", sample.Cpu.TotalCpuPercent), writer);
Set("LOGICAL_CPU_SATURATED", sample.Cpu.MaxLogicalCpuPercent >= config.LogicalCpuSpikePercent, sample,
string.Format(CultureInfo.InvariantCulture, "最高邏輯核心 {0:0.0}%,忙碌核心 {1}", sample.Cpu.MaxLogicalCpuPercent, sample.Cpu.BusyLogicalCores), writer);
Set("GATEWAY_PACKET_LOSS", !string.IsNullOrWhiteSpace(sample.Network.GatewayAddress) && !sample.Network.GatewayPing.Success, sample,
sample.Network.GatewayPing.Success ? "本機到路由器Ping已恢復" : "本機到路由器Ping失敗", writer);
Set("INTERNET_PACKET_LOSS", !sample.Network.InternetPing.Success, sample,
sample.Network.InternetPing.Success ? "外網Ping已恢復" : "外網Ping失敗:" + sample.Network.InternetPing.Status, writer);
Set("GATEWAY_LATENCY_SPIKE", sample.Network.GatewayPing.Success && sample.Network.GatewayPing.RoundtripMs >= config.GatewaySpikeMs, sample,
string.Format(CultureInfo.InvariantCulture, "路由器延遲 {0}ms{1}", sample.Network.GatewayPing.RoundtripMs,
sample.Network.GatewayPing.RoundtripMs >= config.GatewaySpikeMs ? string.Empty : ",已恢復"), writer);
Set("INTERNET_LATENCY_SPIKE", sample.Network.InternetPing.Success && sample.Network.InternetPing.RoundtripMs >= config.InternetSpikeMs, sample,
string.Format(CultureInfo.InvariantCulture, "外網延遲 {0}ms{1}", sample.Network.InternetPing.RoundtripMs,
sample.Network.InternetPing.RoundtripMs >= config.InternetSpikeMs ? string.Empty : ",已恢復"), writer);
bool networkProblem = !sample.Network.InternetPing.Success ||
(sample.Network.InternetPing.Success && sample.Network.InternetPing.RoundtripMs >= config.InternetSpikeMs);
bool cpuProblem = sample.Cpu.TotalCpuPercent >= config.TotalCpuSpikePercent ||
sample.Cpu.MaxLogicalCpuPercent >= config.LogicalCpuSpikePercent;
Set("CPU_NETWORK_CORRELATION", networkProblem && cpuProblem, sample,
"網路異常與CPU高負載同時發生", writer);
}
public void Mark(Sample sample, string details, StreamWriter writer)
{
WriteEvent("USER_MARKER", "MARK", sample, details, writer);
}
private void Set(string eventName, bool active, Sample sample, string details, StreamWriter writer)
{
bool previous;
if (!_states.TryGetValue(eventName, out previous))
{
_states[eventName] = active;
if (!active && eventName != "TARGET_PROCESS_SESSION")
return;
}
if (previous == active)
return;
_states[eventName] = active;
WriteEvent(eventName, active ? "START" : "END", sample, details, writer);
}
private static void WriteEvent(string eventName, string state, Sample sample, string details, StreamWriter writer)
{
writer.WriteLine(string.Join(",", new[]
{
CsvValue(sample.Timestamp.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture)),
sample.ElapsedSeconds.ToString("0.000", CultureInfo.InvariantCulture),
CsvValue(eventName),
state,
CsvValue(details),
sample.Cpu.TotalCpuPercent.ToString("0.0", CultureInfo.InvariantCulture),
sample.Cpu.MaxLogicalCpuPercent.ToString("0.0", CultureInfo.InvariantCulture),
CsvValue(sample.TargetProcessName),
sample.Valorant.IsRunning ? "1" : "0",
sample.Valorant.CpuPercent.ToString("0.0", CultureInfo.InvariantCulture),
sample.Network.GatewayPing.Success ? sample.Network.GatewayPing.RoundtripMs.ToString(CultureInfo.InvariantCulture) : string.Empty,
sample.Network.InternetPing.Success ? sample.Network.InternetPing.RoundtripMs.ToString(CultureInfo.InvariantCulture) : string.Empty,
sample.Network.InternetJitterMs.ToString("0.0", CultureInfo.InvariantCulture),
sample.Network.DownloadKBps.ToString("0.0", CultureInfo.InvariantCulture),
sample.Network.UploadKBps.ToString("0.0", CultureInfo.InvariantCulture)
}));
writer.Flush();
}
private static string CsvValue(string value)
{
if (value == null)
return string.Empty;
if (value.IndexOfAny(new[] { ',', '"', '\r', '\n' }) < 0)
return value;
return "\"" + value.Replace("\"", "\"\"") + "\"";
}
}
internal sealed class SessionStatistics
{
private readonly MonitorConfig _config;
private readonly string _targetProcessName;
private long _samples;
private long _targetProcessSamples;
private double _cpuSum;
private double _maxCpu;
private double _maxLogicalCpu;
private long _cpuSpikeSamples;
private long _gatewaySuccess;
private long _gatewayFailure;
private double _gatewayRttSum;
private long _gatewayMax;
private long _internetSuccess;
private long _internetFailure;
private double _internetRttSum;
private long _internetMax;
private long _internetSpikeSamples;
private double _maxDownload;
private double _maxUpload;
public SessionStatistics(MonitorConfig config, string targetProcessName)
{
_config = config;
_targetProcessName = targetProcessName;
}
public void Add(Sample sample)
{
_samples++;
if (sample.Valorant.IsRunning) _targetProcessSamples++;
_cpuSum += sample.Cpu.TotalCpuPercent;
_maxCpu = Math.Max(_maxCpu, sample.Cpu.TotalCpuPercent);
_maxLogicalCpu = Math.Max(_maxLogicalCpu, sample.Cpu.MaxLogicalCpuPercent);
if (sample.Cpu.TotalCpuPercent >= _config.TotalCpuSpikePercent || sample.Cpu.MaxLogicalCpuPercent >= _config.LogicalCpuSpikePercent)
_cpuSpikeSamples++;
if (sample.Network.GatewayPing.Success)
{
_gatewaySuccess++;
_gatewayRttSum += sample.Network.GatewayPing.RoundtripMs;
_gatewayMax = Math.Max(_gatewayMax, sample.Network.GatewayPing.RoundtripMs);
}
else if (!string.IsNullOrWhiteSpace(sample.Network.GatewayAddress))
_gatewayFailure++;
if (sample.Network.InternetPing.Success)
{
_internetSuccess++;
_internetRttSum += sample.Network.InternetPing.RoundtripMs;
_internetMax = Math.Max(_internetMax, sample.Network.InternetPing.RoundtripMs);
if (sample.Network.InternetPing.RoundtripMs >= _config.InternetSpikeMs)
_internetSpikeSamples++;
}
else
_internetFailure++;
_maxDownload = Math.Max(_maxDownload, sample.Network.DownloadKBps);
_maxUpload = Math.Max(_maxUpload, sample.Network.UploadKBps);
}
public string BuildSummary(DateTime started, DateTime ended, string csvPath, string eventsPath)
{
StringBuilder text = new StringBuilder();
text.AppendLine("NetPulse Session Summary / 監測摘要");
text.AppendLine("=================================");
text.AppendLine("Started / 開始:" + started.ToString("yyyy-MM-dd HH:mm:ss"));
text.AppendLine("Ended / 結束:" + ended.ToString("yyyy-MM-dd HH:mm:ss"));
text.AppendLine("Duration / 總時間:" + (ended - started).ToString());
text.AppendLine("Target process / 監測目標:" + _targetProcessName);
text.AppendLine("Samples / 樣本數:" + _samples.ToString(CultureInfo.InvariantCulture));
text.AppendLine("Target-running samples / 目標程式執行樣本數:" + _targetProcessSamples.ToString(CultureInfo.InvariantCulture));
text.AppendLine();
text.AppendLine(string.Format(CultureInfo.InvariantCulture, "平均CPU:{0:0.0}%", _samples > 0 ? _cpuSum / _samples : 0));
text.AppendLine(string.Format(CultureInfo.InvariantCulture, "最高總CPU:{0:0.0}%", _maxCpu));
text.AppendLine(string.Format(CultureInfo.InvariantCulture, "最高單一邏輯核心:{0:0.0}%", _maxLogicalCpu));
text.AppendLine("CPU高負載樣本:" + _cpuSpikeSamples.ToString(CultureInfo.InvariantCulture));
text.AppendLine();
text.AppendLine(string.Format(CultureInfo.InvariantCulture, "路由器平均/最高Ping:{0:0.0}/{1} ms", _gatewaySuccess > 0 ? _gatewayRttSum / _gatewaySuccess : 0, _gatewayMax));
text.AppendLine(string.Format(CultureInfo.InvariantCulture, "路由器Ping失敗:{0}/{1}", _gatewayFailure, _gatewaySuccess + _gatewayFailure));
text.AppendLine(string.Format(CultureInfo.InvariantCulture, "外網平均/最高Ping:{0:0.0}/{1} ms", _internetSuccess > 0 ? _internetRttSum / _internetSuccess : 0, _internetMax));
text.AppendLine(string.Format(CultureInfo.InvariantCulture, "外網Ping失敗:{0}/{1}", _internetFailure, _internetSuccess + _internetFailure));
text.AppendLine("外網延遲尖峰樣本:" + _internetSpikeSamples.ToString(CultureInfo.InvariantCulture));
text.AppendLine(string.Format(CultureInfo.InvariantCulture, "最高下載/上傳:{0:0.0}/{1:0.0} KB/s", _maxDownload, _maxUpload));
text.AppendLine();
text.AppendLine("完整紀錄:" + csvPath);
text.AppendLine("事件紀錄:" + eventsPath);
return text.ToString();
}
}
internal sealed class Sample
{
public DateTime Timestamp;
public double ElapsedSeconds;
public string Mode;
public string TargetProcessName;
public CpuSnapshot Cpu;
public ProcessCpuSnapshot Valorant;
public NetworkSnapshot Network;
}
internal sealed class SessionResult
{
public DateTime Started;
public DateTime Ended;
public string CsvPath;
public string EventsPath;
public string SummaryPath;
public string SessionDirectory;
public string ErrorMessage;
public string TargetProcessName;
}
internal struct CpuSnapshot
{
public double TotalCpuPercent;
public double MaxLogicalCpuPercent;
public int BusyLogicalCores;
}