├── .gitattributes ├── .gitignore ├── GCStats ├── Allocate │ ├── Allocate.csproj │ ├── Program.cs │ └── Properties │ │ └── launchSettings.json ├── GCStats.sln ├── Shared.cs ├── dotnet-fullgc │ ├── Program.cs │ └── dotnet-fullgc.csproj └── dotnet-gcstats │ ├── Program.cs │ └── dotnet-gcstats.csproj ├── LICENSE └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | artifacts/ 46 | 47 | *_i.c 48 | *_p.c 49 | *_i.h 50 | *.ilk 51 | *.meta 52 | *.obj 53 | *.pch 54 | *.pdb 55 | *.pgc 56 | *.pgd 57 | *.rsp 58 | *.sbr 59 | *.tlb 60 | *.tli 61 | *.tlh 62 | *.tmp 63 | *.tmp_proj 64 | *.log 65 | *.vspscc 66 | *.vssscc 67 | .builds 68 | *.pidb 69 | *.svclog 70 | *.scc 71 | 72 | # Chutzpah Test files 73 | _Chutzpah* 74 | 75 | # Visual C++ cache files 76 | ipch/ 77 | *.aps 78 | *.ncb 79 | *.opendb 80 | *.opensdf 81 | *.sdf 82 | *.cachefile 83 | *.VC.db 84 | *.VC.VC.opendb 85 | 86 | # Visual Studio profiler 87 | *.psess 88 | *.vsp 89 | *.vspx 90 | *.sap 91 | 92 | # TFS 2012 Local Workspace 93 | $tf/ 94 | 95 | # Guidance Automation Toolkit 96 | *.gpState 97 | 98 | # ReSharper is a .NET coding add-in 99 | _ReSharper*/ 100 | *.[Rr]e[Ss]harper 101 | *.DotSettings.user 102 | 103 | # JustCode is a .NET coding add-in 104 | .JustCode 105 | 106 | # TeamCity is a build add-in 107 | _TeamCity* 108 | 109 | # DotCover is a Code Coverage Tool 110 | *.dotCover 111 | 112 | # NCrunch 113 | _NCrunch_* 114 | .*crunch*.local.xml 115 | nCrunchTemp_* 116 | 117 | # MightyMoose 118 | *.mm.* 119 | AutoTest.Net/ 120 | 121 | # Web workbench (sass) 122 | .sass-cache/ 123 | 124 | # Installshield output folder 125 | [Ee]xpress/ 126 | 127 | # DocProject is a documentation generator add-in 128 | DocProject/buildhelp/ 129 | DocProject/Help/*.HxT 130 | DocProject/Help/*.HxC 131 | DocProject/Help/*.hhc 132 | DocProject/Help/*.hhk 133 | DocProject/Help/*.hhp 134 | DocProject/Help/Html2 135 | DocProject/Help/html 136 | 137 | # Click-Once directory 138 | publish/ 139 | 140 | # Publish Web Output 141 | *.[Pp]ublish.xml 142 | *.azurePubxml 143 | # TODO: Comment the next line if you want to checkin your web deploy settings 144 | # but database connection strings (with potential passwords) will be unencrypted 145 | *.pubxml 146 | *.publishproj 147 | 148 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 149 | # checkin your Azure Web App publish settings, but sensitive information contained 150 | # in these scripts will be unencrypted 151 | PublishScripts/ 152 | 153 | # NuGet Packages 154 | *.nupkg 155 | # The packages folder can be ignored because of Package Restore 156 | **/packages/* 157 | # except build/, which is used as an MSBuild target. 158 | !**/packages/build/ 159 | # Uncomment if necessary however generally it will be regenerated when needed 160 | #!**/packages/repositories.config 161 | # NuGet v3's project.json files produces more ignoreable files 162 | *.nuget.props 163 | *.nuget.targets 164 | 165 | # Microsoft Azure Build Output 166 | csx/ 167 | *.build.csdef 168 | 169 | # Microsoft Azure Emulator 170 | ecf/ 171 | rcf/ 172 | 173 | # Windows Store app package directories and files 174 | AppPackages/ 175 | BundleArtifacts/ 176 | Package.StoreAssociation.xml 177 | _pkginfo.txt 178 | 179 | # Visual Studio cache files 180 | # files ending in .cache can be ignored 181 | *.[Cc]ache 182 | # but keep track of directories ending in .cache 183 | !*.[Cc]ache/ 184 | 185 | # Others 186 | ClientBin/ 187 | ~$* 188 | *~ 189 | *.dbmdl 190 | *.dbproj.schemaview 191 | *.pfx 192 | *.publishsettings 193 | node_modules/ 194 | orleans.codegen.cs 195 | 196 | # Since there are multiple workflows, uncomment next line to ignore bower_components 197 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 198 | #bower_components/ 199 | 200 | # RIA/Silverlight projects 201 | Generated_Code/ 202 | 203 | # Backup & report files from converting an old project file 204 | # to a newer Visual Studio version. Backup files are not needed, 205 | # because we have git ;-) 206 | _UpgradeReport_Files/ 207 | Backup*/ 208 | UpgradeLog*.XML 209 | UpgradeLog*.htm 210 | 211 | # SQL Server files 212 | *.mdf 213 | *.ldf 214 | 215 | # Business Intelligence projects 216 | *.rdl.data 217 | *.bim.layout 218 | *.bim_*.settings 219 | 220 | # Microsoft Fakes 221 | FakesAssemblies/ 222 | 223 | # GhostDoc plugin setting file 224 | *.GhostDoc.xml 225 | 226 | # Node.js Tools for Visual Studio 227 | .ntvs_analysis.dat 228 | 229 | # Visual Studio 6 build log 230 | *.plg 231 | 232 | # Visual Studio 6 workspace options file 233 | *.opt 234 | 235 | # Visual Studio LightSwitch build output 236 | **/*.HTMLClient/GeneratedArtifacts 237 | **/*.DesktopClient/GeneratedArtifacts 238 | **/*.DesktopClient/ModelManifest.xml 239 | **/*.Server/GeneratedArtifacts 240 | **/*.Server/ModelManifest.xml 241 | _Pvt_Extensions 242 | 243 | # Paket dependency manager 244 | .paket/paket.exe 245 | paket-files/ 246 | 247 | # FAKE - F# Make 248 | .fake/ 249 | 250 | # JetBrains Rider 251 | .idea/ 252 | *.sln.iml 253 | -------------------------------------------------------------------------------- /GCStats/Allocate/Allocate.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /GCStats/Allocate/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using System.Runtime; 4 | using System.Threading; 5 | 6 | namespace Allocate 7 | { 8 | internal class Program 9 | { 10 | static void Main(string[] args) 11 | { 12 | int maxGarbageCollectionsCount = 10; 13 | 14 | if (args.Length == 1) 15 | { 16 | maxGarbageCollectionsCount = int.Parse(args[0]); 17 | } 18 | 19 | Console.WriteLine($"Initial GCSettings.LatencyMode = {GCSettings.LatencyMode}"); 20 | GCSettings.LatencyMode = GCLatencyMode.Interactive; 21 | Console.WriteLine($"GCSettings.LatencyMode = {GCSettings.LatencyMode}"); 22 | Console.WriteLine($"Server GC = {GCSettings.IsServerGC}"); 23 | Console.WriteLine($"pid = {Process.GetCurrentProcess().Id}"); 24 | Console.ReadLine(); 25 | 26 | // trigger induced GC 27 | //GC.Collect(2, GCCollectionMode.Forced); 28 | GC.Collect(2, GCCollectionMode.Aggressive); 29 | 30 | // allocate to trigger 10 garbage collections 31 |      const int LEN = 1_000_000; 32 | byte[][] list = new byte[LEN][]; 33 | for (int i = 0; i < LEN; ++i) 34 | { 35 | list[i] = new byte[25000]; 36 | if (i % 100 == 0) 37 | { 38 | Console.WriteLine("Allocated 100 arrays"); 39 | Thread.Sleep(500); 40 | if (GC.CollectionCount(0) >= maxGarbageCollectionsCount) 41 | { 42 | Console.WriteLine($"Leaving at i = {i}"); 43 | Console.WriteLine($" #gen0 = {GC.CollectionCount(0)}"); 44 | Console.WriteLine($" #gen1 = {GC.CollectionCount(1)}"); 45 | Console.WriteLine($" #gen2 = {GC.CollectionCount(2)}"); 46 | break; 47 | } 48 | } 49 | } 50 | 51 | Console.WriteLine("Press any key to exit..."); 52 | Console.Read(); 53 | } 54 | } 55 | } -------------------------------------------------------------------------------- /GCStats/Allocate/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "Allocate": { 4 | "commandName": "Project", 5 | "commandLineArgs": "12", 6 | "environmentVariables": { 7 | "DOTNET_gcServer": "0", 8 | "DOTNET_GCLatencyLevel": "1", 9 | "DOTNET_gcConcurrent": "0" 10 | } 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /GCStats/GCStats.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.7.34003.232 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "dotnet-gcstats", "dotnet-gcstats\dotnet-gcstats.csproj", "{F347A65E-5EDC-4DFD-975F-53F6524BD028}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Allocate", "Allocate\Allocate.csproj", "{4CA8125F-92E9-4EA5-A7D1-A9972B813FD3}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dotnet-fullgc", "dotnet-fullgc\dotnet-fullgc.csproj", "{61F728DA-AE62-4E49-9ED6-18DF34E7AF24}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {F347A65E-5EDC-4DFD-975F-53F6524BD028}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {F347A65E-5EDC-4DFD-975F-53F6524BD028}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {F347A65E-5EDC-4DFD-975F-53F6524BD028}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {F347A65E-5EDC-4DFD-975F-53F6524BD028}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {4CA8125F-92E9-4EA5-A7D1-A9972B813FD3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {4CA8125F-92E9-4EA5-A7D1-A9972B813FD3}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {4CA8125F-92E9-4EA5-A7D1-A9972B813FD3}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {4CA8125F-92E9-4EA5-A7D1-A9972B813FD3}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {61F728DA-AE62-4E49-9ED6-18DF34E7AF24}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {61F728DA-AE62-4E49-9ED6-18DF34E7AF24}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {61F728DA-AE62-4E49-9ED6-18DF34E7AF24}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {61F728DA-AE62-4E49-9ED6-18DF34E7AF24}.Release|Any CPU.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {7DAE7A90-3FF9-47E5-BFC8-568AE5FAE8BC} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /GCStats/Shared.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Diagnostics.Tracing.Parsers.Clr; 2 | using System; 3 | 4 | 5 | class Shared 6 | { 7 | public static void WriteWithColor(string text, ConsoleColor color) 8 | { 9 | var current = Console.ForegroundColor; 10 | Console.ForegroundColor = color; 11 | Console.Write(text); 12 | Console.ForegroundColor = current; 13 | } 14 | 15 | public static ConsoleColor GetGenColor(int gen) 16 | { 17 | switch (gen) 18 | { 19 | case 2: return ConsoleColor.Blue; 20 | case 1: return ConsoleColor.DarkCyan; 21 | case 0: return ConsoleColor.Cyan; 22 | default: 23 | return ConsoleColor.White; 24 | } 25 | } 26 | 27 | 28 | public const int gen_initial = 0; // indicates the initial gen to condemn. 29 | public const int gen_final_per_heap = 1; // indicates the final gen to condemn per heap. 30 | public const int gen_alloc_budget = 2; // indicates which gen's budget is exceeded. 31 | 32 | private const int InitialGenMask = 0x0 + 0x1 + 0x2; 33 | 34 | public static int GetGen(int val, int reason) 35 | { 36 | int gen = (val >> 2 * reason) & InitialGenMask; 37 | return gen; 38 | } 39 | 40 | 41 | public static void DumpGlobalMechanisms(GCGlobalMechanisms gm) 42 | { 43 | string[] mechanisms = $"{gm}".Split(", "); 44 | int count = mechanisms.Length; 45 | for (int i = 0; i < count; i++) 46 | { 47 | if (mechanisms[i] == "Compaction") 48 | { 49 | Shared.WriteWithColor(mechanisms[i], ConsoleColor.DarkYellow); 50 | } 51 | else 52 | if (mechanisms[i] == "Concurrent") 53 | { 54 | Shared.WriteWithColor(mechanisms[i], ConsoleColor.DarkGreen); 55 | } 56 | else 57 | { 58 | Console.Write(mechanisms[i]); 59 | } 60 | 61 | if (i < count - 1) 62 | { 63 | Console.Write(", "); 64 | } 65 | } 66 | } 67 | 68 | public enum GCReasonNet8 69 | { 70 | AllocSmall, 71 | Induced, 72 | LowMemory, 73 | Empty, 74 | AllocLarge, 75 | OutOfSpaceSOH, 76 | OutOfSpaceLOH, 77 | InducedNotForced, 78 | Internal, 79 | InducedLowMemory, 80 | InducedCompacting, 81 | LowMemoryHost, 82 | PMFullGC, 83 | LowMemoryHostBlocking, 84 | // 85 | // new ones 86 | BgcTuningSOH, 87 | BgcTuningLOH, 88 | BgcStepping, 89 | InducedAggressive, 90 | } 91 | 92 | [Flags] 93 | public enum CondemnReasonCondition 94 | { 95 | no_condemn_reason_condition = 0, 96 | induced_fullgc = 0x1, 97 | expand_fullgc = 0x2, 98 | high_mem = 0x4, 99 | very_high_mem = 0x8, 100 | low_ephemeral = 0x10, 101 | low_card = 0x20, 102 | eph_high_frag = 0x40, 103 | max_high_frag = 0x80, 104 | max_high_frag_e = 0x100, 105 | max_high_frag_m = 0x200, 106 | max_high_frag_vm = 0x400, 107 | max_gen1 = 0x800, 108 | before_oom = 0x1000, 109 | gen2_too_small = 0x2000, 110 | induced_noforce = 0x4000, 111 | before_bgc = 0x8000, 112 | almost_max_alloc = 0x10000, 113 | joined_avoid_unproductive = 0x20000, 114 | joined_pm_induced_fullgc = 0x40000, 115 | joined_pm_alloc_loh = 0x80000, 116 | joined_gen1_in_pm = 0x100000, 117 | joined_limit_before_oom = 0x200000, 118 | joined_limit_loh_frag = 0x400000, 119 | joined_limit_loh_reclaim = 0x800000, 120 | joined_servo_initial = 0x1000000, 121 | joined_servo_ngc = 0x2000000, 122 | joined_servo_bgc = 0x4000000, 123 | joined_servo_postpone = 0x8000000, 124 | joined_stress_mix = 0x10000000, 125 | joined_stress = 0x20000000, 126 | gcrc_max = 0x40000000 127 | } 128 | } -------------------------------------------------------------------------------- /GCStats/dotnet-fullgc/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Reflection; 4 | using System.Diagnostics.Tracing; 5 | using Microsoft.Diagnostics.NETCore.Client; 6 | using Microsoft.Diagnostics.Tracing.Parsers; 7 | using System.Threading.Tasks; 8 | using System.Threading; 9 | using Microsoft.Diagnostics.Tracing; 10 | 11 | 12 | namespace dotnet_fullgc 13 | { 14 | internal class Program 15 | { 16 | private const string name = "dotnet-fullgc"; 17 | private static Version version = Assembly.GetExecutingAssembly().GetName().Version; 18 | 19 | static void Main(string[] args) 20 | { 21 | if (args.Length == 0) 22 | { 23 | ShowHelp(name, version.ToString(), "No process ID specified"); 24 | return; 25 | } 26 | 27 | int pid = -1; 28 | if (!int.TryParse(args[0], out pid)) 29 | { 30 | ShowHelp(name, version.ToString(), $"Invalid specified process ID '{args[0]}'"); 31 | return; 32 | } 33 | 34 | Int64 clientSequenceNumber = 0; 35 | if (args.Length > 2) 36 | { 37 | if (args[1] == "-csn") 38 | { 39 | if (!Int64.TryParse(args[2], out clientSequenceNumber)) 40 | { 41 | ShowHelp(name, version.ToString(), $"Invalid client sequence number '{args[2]}'"); 42 | return; 43 | } 44 | } 45 | } 46 | else 47 | { 48 | ShowHelp(name, version.ToString(), $"Invalid option '{args[1]}'"); 49 | return; 50 | } 51 | 52 | ShowHeader(name, version.ToString()); 53 | try 54 | { 55 | TriggerGC(pid, clientSequenceNumber); 56 | } 57 | catch (Exception x) 58 | { 59 | ShowError(x.Message); 60 | } 61 | } 62 | 63 | private static void TriggerGC(int processId, Int64 clientSequenceNumber) 64 | { 65 | // Note: this client sequence number is not processed before .NET 9 66 | Dictionary arguments = new Dictionary(); 67 | arguments.Add("Id", clientSequenceNumber.ToString()); 68 | var providers = new List() 69 | { 70 | new EventPipeProvider( 71 | "Microsoft-Windows-DotNETRuntime", 72 | EventLevel.Informational, 73 | (long)ClrTraceEventParser.Keywords.GCHeapCollect, 74 | arguments 75 | ), 76 | }; 77 | var client = new DiagnosticsClient(processId); 78 | 79 | using (var session = client.StartEventPipeSession(providers, false)) 80 | { 81 | Console.WriteLine("Sending command..."); 82 | Task streamTask = Task.Run(() => 83 | { 84 | // without source to process, session.Stop() will not return 85 | var source = new EventPipeEventSource(session.EventStream); 86 | 87 | // No GCStart event is received in that case :^( 88 | //ClrTraceEventParser clrParser = new ClrTraceEventParser(source); 89 | //clrParser.GCStart += OnGCStart; 90 | 91 | try 92 | { 93 | source.Process(); 94 | } 95 | catch (Exception e) 96 | { 97 | ShowError($"Error encountered while processing event source: {e.Message}"); 98 | } 99 | }); 100 | 101 | Task inputTask = Task.Run(() => 102 | { 103 | Thread.Sleep(1000); 104 | session.Stop(); 105 | }); 106 | 107 | Task.WaitAny(streamTask, inputTask); 108 | 109 | Console.WriteLine("Full GC has been triggered"); 110 | } 111 | } 112 | 113 | static void ShowHelp(string name, string version, string message) 114 | { 115 | Console.WriteLine(string.Format(Header, name, version)); 116 | if (string.IsNullOrEmpty(message)) 117 | { 118 | return; 119 | } 120 | 121 | Console.WriteLine(); 122 | Console.WriteLine(message); 123 | Console.WriteLine(); 124 | Console.WriteLine(Help, name); 125 | } 126 | 127 | static void ShowError(string message) 128 | { 129 | if (string.IsNullOrEmpty(message)) 130 | { 131 | return; 132 | } 133 | 134 | Console.WriteLine(); 135 | Console.WriteLine(message); 136 | } 137 | 138 | static void ShowHeader(string name, string version) 139 | { 140 | Console.WriteLine(string.Format(Header, name, version)); 141 | } 142 | 143 | 144 | private static string Header = 145 | "{0} v{1}" + Environment.NewLine + 146 | "by Christophe Nasarre" + Environment.NewLine + 147 | "Trigger a full garbage collections in a .NET application"; 148 | private static string Help = 149 | "Usage: {0} [-csn ]" + Environment.NewLine + 150 | ""; 151 | 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /GCStats/dotnet-fullgc/dotnet-fullgc.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | dotnet_fullgc 7 | true 8 | dotnet-fullgc 9 | ./nupkg 10 | true 11 | 12 | 13 | 14 | dotnet-fullgc 15 | 1.1.0 16 | dotnet-fullgc 17 | christophe Nasarre 18 | chrisnas 19 | https://github.com/chrisnas 20 | git 21 | https://github.com/chrisnas/GCStats 22 | LICENSE 23 | Global CLI tool to trigger full .NET garbage collections 24 | Initial release 25 | Copyright Christophe Nasarre 2024-$([System.DateTime]::UtcNow.ToString(yyyy)) 26 | .NET TraceEvent CLR GC 27 | README.md 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /GCStats/dotnet-gcstats/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Diagnostics.NETCore.Client; 2 | using Microsoft.Diagnostics.Tracing.Parsers.Clr; 3 | using Microsoft.Diagnostics.Tracing.Parsers; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Diagnostics.Tracing; 7 | using System.Threading.Tasks; 8 | using Microsoft.Diagnostics.Tracing; 9 | using System.Threading; 10 | using System.Reflection; 11 | 12 | namespace GCStats 13 | { 14 | internal class Program 15 | { 16 | private const string name = "dotnet-gcstats"; 17 | private static Version version = Assembly.GetExecutingAssembly().GetName().Version; 18 | private static bool _isVerbose = false; 19 | 20 | static void Main(string[] args) 21 | { 22 | if (args.Length == 0) 23 | { 24 | ShowHelp(name, version.ToString(), "No process ID specified"); 25 | return; 26 | } 27 | 28 | int pid = -1; 29 | if (!int.TryParse(args[0], out pid)) 30 | { 31 | ShowHelp(name, version.ToString(), $"Invalid specified process ID '{args[0]}'"); 32 | return; 33 | } 34 | 35 | if (args.Length > 1) 36 | { 37 | if (args[1] == "-v") 38 | { 39 | _isVerbose = true; 40 | } 41 | else 42 | { 43 | ShowHelp(name, version.ToString(), $"Invalid option '{args[1]}'"); 44 | return; 45 | } 46 | } 47 | 48 | ShowHeader(name, version.ToString()); 49 | try 50 | { 51 | PrintEventsLive(pid); 52 | } 53 | catch (Exception x) 54 | { 55 | ShowError(x.Message); 56 | } 57 | } 58 | 59 | 60 | public static void PrintEventsLive(int processId) 61 | { 62 | var providers = new List() 63 | { 64 | new EventPipeProvider("Microsoft-Windows-DotNETRuntime", 65 | EventLevel.Informational, (long)ClrTraceEventParser.Keywords.GC), 66 | }; 67 | var client = new DiagnosticsClient(processId); 68 | 69 | using (var session = client.StartEventPipeSession(providers, false)) 70 | { 71 | Console.WriteLine(); 72 | 73 | Task streamTask = Task.Run(() => 74 | { 75 | var source = new EventPipeEventSource(session.EventStream); 76 | 77 | ClrTraceEventParser clrParser = new ClrTraceEventParser(source); 78 | clrParser.GCPerHeapHistory += OnGCPerHeapHistory; 79 | clrParser.GCStart += OnGCStart; 80 | clrParser.GCGlobalHeapHistory += OnGCGlobalHeapHistory; 81 | 82 | // to get all other events 83 | //clrParser.All += ClrParser_All; 84 | 85 | try 86 | { 87 | source.Process(); 88 | } 89 | catch (Exception e) 90 | { 91 | ShowError($"Error encountered while processing events: {e.Message}"); 92 | } 93 | }); 94 | 95 | Task inputTask = Task.Run(() => 96 | { 97 | while (Console.ReadKey().Key != ConsoleKey.Enter) 98 | { 99 | Thread.Sleep(100); 100 | } 101 | session.Stop(); 102 | }); 103 | 104 | Task.WaitAny(streamTask, inputTask); 105 | } 106 | } 107 | 108 | private static void ClrParser_All(TraceEvent eventData) 109 | { 110 | if ( 111 | (eventData.ID == (TraceEventID)1) || 112 | (eventData.ID == (TraceEventID)204) || 113 | (eventData.ID == (TraceEventID)205) 114 | ) 115 | { 116 | return; 117 | } 118 | 119 | Console.WriteLine($"{eventData.ID,4} - {eventData.OpcodeName} | {eventData.EventName}"); 120 | } 121 | 122 | private static void OnGCStart(GCStartTraceData payload) 123 | { 124 | Console.WriteLine(); 125 | Console.Write($"_______#{payload.Count}"); 126 | Shared.WriteWithColor($" gen{payload.Depth}", Shared.GetGenColor(payload.Depth)); 127 | 128 | Shared.GCReasonNet8 reason = (Shared.GCReasonNet8)payload.Reason; 129 | if ( 130 | (reason == Shared.GCReasonNet8.Induced) || 131 | (reason == Shared.GCReasonNet8.InducedNotForced) || 132 | (reason == Shared.GCReasonNet8.InducedCompacting) || 133 | (reason == Shared.GCReasonNet8.InducedAggressive) 134 | ) 135 | { 136 | Console.Write(" = "); 137 | Shared.WriteWithColor($"{(Shared.GCReasonNet8)payload.Reason}", ConsoleColor.Red); 138 | if (payload.ClientSequenceNumber != 0) 139 | { 140 | Shared.WriteWithColor($" ##{payload.ClientSequenceNumber}", ConsoleColor.Magenta); 141 | } 142 | Console.WriteLine(); 143 | } 144 | else 145 | { 146 | Console.WriteLine($" = {(Shared.GCReasonNet8)payload.Reason}"); 147 | } 148 | } 149 | 150 | private static void OnGCGlobalHeapHistory(GCGlobalHeapHistoryTraceData payload) 151 | { 152 | Console.Write($".......< "); 153 | Shared.WriteWithColor($"gen{payload.CondemnedGeneration}", Shared.GetGenColor(payload.CondemnedGeneration)); 154 | Console.Write($" {payload.PauseMode} ["); 155 | Shared.DumpGlobalMechanisms(payload.GlobalMechanisms); 156 | Console.WriteLine($"] mem pressure = {payload.MemoryPressure}"); 157 | } 158 | 159 | private static void OnGCPerHeapHistory(GCPerHeapHistoryTraceData payload) 160 | { 161 | if (payload.HeapIndex == 0) 162 | { 163 | var condemnReasonCondition = (payload.CondemnReasons1 == 0) ? "" : $"{(Shared.CondemnReasonCondition)payload.CondemnReasons1}"; 164 | int startGen = Shared.GetGen(payload.CondemnReasons0, Shared.gen_initial); 165 | int finalGen = Shared.GetGen(payload.CondemnReasons0, Shared.gen_final_per_heap); 166 | var startGenColor = Shared.GetGenColor(startGen); 167 | var finalGenColor = Shared.GetGenColor(finalGen); 168 | Console.Write($" condemn "); 169 | Shared.WriteWithColor($"gen{startGen}", startGenColor); 170 | Console.Write($" -> "); 171 | Shared.WriteWithColor($"gen{finalGen}", finalGenColor); 172 | Console.WriteLine($" [budget gen{Shared.GetGen(payload.CondemnReasons0, Shared.gen_alloc_budget)}] {condemnReasonCondition}"); 173 | 174 | if (_isVerbose) 175 | { 176 | Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); 177 | } 178 | } 179 | 180 | if (!_isVerbose) 181 | { 182 | return; 183 | } 184 | 185 | Console.WriteLine($" heap #{payload.HeapIndex,2} Gen0 Gen1 Gen2 LOH POH"); 186 | Console.WriteLine("-----------------------------------------------------------------------------"); 187 | var entryCount = payload.EntriesInGenData; 188 | var gen0 = payload.GenData(Gens.Gen0); 189 | var gen1 = payload.GenData(Gens.Gen1); 190 | var gen2 = payload.GenData(Gens.Gen2); 191 | var loh = payload.GenData(Gens.GenLargeObj); 192 | var poh = payload.GenData(Gens.GenPinObj); 193 | 194 | Console.WriteLine($" Budget {(gen0.Budget),10} {(gen1.Budget),10} {(gen2.Budget),10} {(loh.Budget),10} {(poh.Budget),10} "); 195 | Console.WriteLine($" Begin size {(gen0.SizeBefore),10} {(gen1.SizeBefore),10} {(gen2.SizeBefore),10} {(loh.SizeBefore),10} {(poh.SizeBefore),10} "); 196 | Console.WriteLine($"Begin obj size {(gen0.ObjSpaceBefore),10} {(gen1.ObjSpaceBefore),10} {(gen2.ObjSpaceBefore),10} {(loh.ObjSpaceBefore),10} {(poh.ObjSpaceBefore),10} "); 197 | Console.WriteLine($" Final size {(gen0.SizeAfter),10} {(gen1.SizeAfter),10} {(gen2.SizeAfter),10} {(loh.SizeAfter),10} {(poh.SizeAfter),10} "); 198 | Console.WriteLine($" Promoted size {(gen0.PinnedSurv + gen0.NonePinnedSurv),10} {(gen1.PinnedSurv + gen1.NonePinnedSurv),10} {(gen2.PinnedSurv + gen2.NonePinnedSurv),10} {(loh.PinnedSurv + loh.NonePinnedSurv),10} {(poh.PinnedSurv + poh.NonePinnedSurv),10} "); 199 | Console.WriteLine($" Fragmentation {(gen0.Fragmentation),10} {(gen1.Fragmentation),10} {(gen2.Fragmentation),10} {(loh.Fragmentation),10} {(poh.Fragmentation),10} "); 200 | Console.WriteLine(); 201 | } 202 | 203 | 204 | static void ShowHelp(string name, string version, string message) 205 | { 206 | Console.WriteLine(string.Format(Header, name, version)); 207 | if (string.IsNullOrEmpty(message)) 208 | { 209 | return; 210 | } 211 | 212 | Console.WriteLine(); 213 | Console.WriteLine(message); 214 | Console.WriteLine(); 215 | Console.WriteLine(Help, name); 216 | } 217 | 218 | static void ShowError(string message) 219 | { 220 | if (string.IsNullOrEmpty(message)) 221 | { 222 | return; 223 | } 224 | 225 | Console.WriteLine(); 226 | Console.WriteLine(message); 227 | } 228 | 229 | static void ShowHeader(string name, string version) 230 | { 231 | Console.WriteLine(string.Format(Header, name, version)); 232 | } 233 | 234 | 235 | private static string Header = 236 | "{0} v{1}" + Environment.NewLine + 237 | "by Christophe Nasarre" + Environment.NewLine + 238 | "Displays live statistics about garbage collections in a .NET application"; 239 | private static string Help = 240 | "Usage: {0} [-v]" + Environment.NewLine + 241 | ""; 242 | } 243 | } -------------------------------------------------------------------------------- /GCStats/dotnet-gcstats/dotnet-gcstats.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | GCStats 7 | true 8 | dotnet-gcstats 9 | ./nupkg 10 | true 11 | 12 | 13 | 14 | dotnet-gcstats 15 | 1.1.0 16 | dotnet-gcstats 17 | christophe Nasarre 18 | chrisnas 19 | https://github.com/chrisnas 20 | git 21 | https://github.com/chrisnas/GCStats 22 | LICENSE 23 | Global CLI tool to display live statistics during .NET garbage collections 24 | Initial release 25 | Copyright Christophe Nasarre 2024-$([System.DateTime]::UtcNow.ToString(yyyy)) 26 | .NET TraceEvent CLR GC 27 | README.md 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Nasarre Christophe 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # dotnet-gcstats 2 | Display live statistics during .NET garbage collections 3 | 4 | # dotnet-fullgc 5 | trigger full .NET garbage collections 6 | --------------------------------------------------------------------------------