Profiling

suggest change

Profiling is the process of measuring a running .NET application's resource consumption—specifically CPU utilization, memory allocations, garbage collection pauses, and thread contention—to identify performance bottlenecks without guesswork.

In modern .NET, profiling can be performed non-invasively in production using the official cross-platform CLI diagnostic tools (dotnet-trace, dotnet-gcdump, dotnet-counters) or locally using the Visual Studio Performance Profiler.


1. The .NET Diagnostic CLI Toolkit

Microsoft provides standalone, cross-platform diagnostic CLI tools that attach to any running .NET Core or .NET 5+ process without modifying application binaries or restarting the server.

Installation

dotnet tool install -g dotnet-trace
dotnet tool install -g dotnet-gcdump
dotnet tool install -g dotnet-counters
dotnet tool install -g dotnet-dump

To list all running .NET processes on the machine:

dotnet-trace ps

2. CPU and Call-Stack Profiling with dotnet-trace

dotnet-trace collects call-stack samples over time to generate flame graphs and call trees.

Collecting a CPU Trace

# Collect CPU sampling profile for a running process
dotnet-trace collect --process-id 18452

# Or launch a process and profile it immediately from startup
dotnet-trace collect -- myapp.exe

Press Ctrl+C or Enter to stop recording. By default, dotnet-trace produces a .nettrace file.

Converting to SpeedScope for Web Viewing

You can convert the trace into Speedscope format to visualize interactive flame graphs in any browser:

dotnet-trace convert myapp_20261017_1745.nettrace --format Speedscope

Open speedscope.app and load the generated .json file to examine call trees, top self-time methods, and execution timelines.


3. Real-Time Performance Monitoring with dotnet-counters

dotnet-counters monitors core runtime metrics in real time (similar to top or Task Manager):

dotnet-counters monitor -p 18452 --counters System.Runtime

Live output for a .NET 9+ app (which publishes the System.Runtime meter; values are machine-dependent) looks like:

Name                                                         Current Value
[System.Runtime]
    dotnet.assembly.count ({assembly})                              12
    dotnet.gc.collections ({collection})
        gc.heap.generation
        ------------------
        gen0                                                       842
        gen1                                                         3
        gen2                                                         0
    dotnet.gc.heap.total_allocated (By)                    912,457,216
    dotnet.gc.last_collection.memory.committed_size (By)    10,354,688
    dotnet.gc.pause.time (s)                                     0.041
    dotnet.monitor.lock_contentions ({contention})                   0
    dotnet.process.cpu.time (s)
        cpu.mode
        --------
        system                                                    0.36
        user                                                      2.91
    dotnet.process.memory.working_set (By)                  41,295,872
    dotnet.thread_pool.queue.length ({work_item})                    0
    dotnet.thread_pool.thread.count ({thread})                       1

Apps on .NET 8 and older publish the legacy System.Runtime EventCounters instead, shown with names such as CPU Usage (%), GC Heap Size (MB) and Gen 0 GC Count.


4. Memory Profiling and Leak Detection with dotnet-gcdump

When diagnosing suspected memory leaks, dotnet-gcdump takes a lightweight snapshot of the managed object graph without pausing process execution or dumping physical memory:

# Capture snapshot 1
dotnet-gcdump collect -p 18452 -o baseline.gcdump

# ... simulate traffic / run workload ...

# Capture snapshot 2
dotnet-gcdump collect -p 18452 -o post_workload.gcdump

Open both .gcdump files in Visual Studio via File -> Open -> File to diff the heaps:


5. Visual Studio Performance Profiler (Alt + F2)

Inside Visual Studio, open the Debug -> Performance Profiler window:

  1. CPU Usage: Generates an interactive flame graph and identifies the "Hot Path" consuming the most execution time.
  2. .NET Object Allocation Tracking: Identifies exact source code lines creating the most heap allocations, distinguishing Gen 0, Gen 1, Gen 2, and Large Object Heap (LOH) allocations.
  3. .NET Counters: Visualizes real-time thread pool starvation and memory trends alongside execution traces.

6. Programmatic Instrumentation with EventSource

You can emit custom metrics and diagnostic traces directly into the .NET runtime tracing infrastructure using EventSource:

using System.Diagnostics.Tracing;

[EventSource(Name = "MyCompany-OrderProcessing")]
public sealed class OrderEventSource : EventSource
{
    public static readonly OrderEventSource Log = new();

    [Event(1, Level = EventLevel.Informational, Message = "Order processed in {0} ms")]
    public void OrderProcessed(long elapsedMilliseconds)
    {
        WriteEvent(1, elapsedMilliseconds);
    }

    [Event(2, Level = EventLevel.Warning, Message = "Order processing delayed: {0}")]
    public void OrderDelayed(string reason)
    {
        WriteEvent(2, reason);
    }
}

// In business logic:
OrderEventSource.Log.OrderProcessed(142);

These events can be captured by dotnet-trace or forwarded to OpenTelemetry and APM collectors.


7. Golden Rules of Profiling

  1. Always Profile Release Builds: Debug builds do not inline methods, leave dead-code branches intact, and generate unnecessary stack-spilling. Never base performance decisions on Debug execution.
  2. Profile with Realistic Workloads: Synthetic micro-benchmarks do not capture garbage collection interference, network latency, or database contention present under production load.
  3. Address Allocations First: In C#, high CPU usage is frequently an indirect consequence of aggressive garbage collection caused by excessive temporary object allocations.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents